Could anyone please point out whats wrong with this code. I am trying to return the thread through a variable flag, which I want to control in my main thread.
test27.py
import threading
import timelock = threading.Lock()def Read(x,y):flag = 1while True:lock.acquire()try:z = x+y; w = x-yprint z*wtime.sleep(1)if flag == 0:print "ABORTING"returnfinally:print " SINGLE run of thread executed"lock.release()
test28.py
import time, threadingfrom test27 import Readprint "Hello Welcome"
a = 2; b = 5
t = threading.Thread(target = Read, name = 'Example Thread', args = (a,b))
t.start()
time.sleep(5)
t.flag = 0 # This is not updating the flag variable in Read FUNCTION
t.join() # Because of the above command I am unable to wait until the thread finishes. It is blocking.
print "PROGRAM ENDED"
The Thread
class can be instantiated with the target
argument. Then you just give it a function which should be executed in a new thread. It is a convenient way to start a simple thread, but for more control it is usually easier to have a class inherited from Thread
, which has additional member variables, like the flag
for aborting.
For example:
import time
import threadingclass MyThread(threading.Thread):def __init__(self, x, y):super().__init__()# or in Python 2:# super(MyThread, self).__init__()self.x = xself.y = yself._stop_requested = Falsedef run(self):while not self._stop_requested:z = self.x + self.yw = self.x - self.yprint (z * w)time.sleep(1)def stop(self, timeout=None):self._stop_requested = Trueself.join(timeout)
Then, to start the thread, call start()
and then to stop it call stop()
:
>>> def run_thread_for_5_seconds():
... t = MyThread(3, 4)
... t.start()
... time.sleep(5)
... t.stop()
...
>>> run_thread_for_5_seconds()
-7
-7
-7
-7
-7
>>>