I already asked my question but It was too complicated to understand. So it is the question in a very simple way. What I want is to have flow control on a loop with thread in a class in python3. Suppose this code:
import threading
from time import sleep
class someclass(threading.Thread):
def __init__(self):
super(someclass, self).__init__()
self.stop_event = False
def poll(self):
print("your main function is running")
for i in range (0,50):
print("i=",i)
sleep(0.5)
def stop(self):
print("stopping the thread")
self.stop_event = True
def stopped(self):
return self.stop_event
def run(self):
print("stop_event: ",self.stop_event)
while not self.stopped():
for i in range (0,50):
print("i=",i)
sleep(0.5)
if __name__=='__main__':
thr=someclass()
print("starting the thread #1")
thr.start()
sleep(10)
print("stopping the thread #1")
thr.stop()
sleep(10)
thr2=someclass()
print("starting the thread #2")
thr2.start()
sleep(10)
print("stopping the thread #2")
thr2.stop()
sleep(10)
print("Exiting the whole program")
so the output would be something like this:
starting the thread #1
stop_event: False
i= 0
i= 1
...
i= 17
i= 18
i= 19
stopping the thread #1
stopping the thread
i= 20
i= 21
i= 22
...
i= 38
i= 39
starting the thread #2
stop_event: False
i= 0
i= 40
i= 1
i= 41
i= 2
i= 42
i= 3
After stopping the thread with thr.stop() it continues to print the i contents but the value of self.stop_event has been set to True. what I want is to control a the looping whenever I want and of course I want it to be in a class not in a main body of my program.
run(), the variableself.stopped()is checked only when the wholerange(50)has been printed, so it cannot detect the stop event before that.timeoutparameter that you can use to unblock them now and then. There are some hacks on the web to raise exception in a thread from another thread. This could be a way but portability issues may occur (between platforms/implementations of python/versions of python). There may be other techniques that I don't know.