Python Threading: Making The Thread Function Return From An External Signal
Solution 1:
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 threading
classMyThread(threading.Thread):
def__init__(self, x, y):
super().__init__()
# or in Python 2:# super(MyThread, self).__init__()
self.x = x
self.y = y
self._stop_requested = Falsedefrun(self):
whilenot self._stop_requested:
z = self.x + self.y
w = self.x - self.y
print (z * w)
time.sleep(1)
defstop(self, timeout=None):
self._stop_requested = True
self.join(timeout)
Then, to start the thread, call start()
and then to stop it call stop()
:
>>>defrun_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
>>>
Solution 2:
Regular variables should not be tracked in threads. This is done to prevent race condition. You must use thread-safe constructs to communicate between threads. For a simple flag use threading.Event
. Also you cannot access local variable flag
via thread object. It is local, and is only visible from scope. You must either use a global variable, as in my example below or create an Object before calling your thread and use a member variable.
from threading import Event
flag = Event()
defRead(x,y):
global flag
flag.clear()
...
if flag.is_set():
return
main thread:
sleep(5)
flag.set()
P.S.: I just noticed that you attempted to use lock() in the thread, but failed to use it in the main thread. For a simple flag go with Event. For a lock() you need to lock both parts and mitigate a risk of a deadlock.
Post a Comment for "Python Threading: Making The Thread Function Return From An External Signal"