Python Threading: Making the thread function return from an external signal
<p>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. </p>

<h1>test27.py</h1>

<pre><code>import threading
import time

lock = threading.Lock()

def Read(x,y):
    flag = 1
    while True:
        lock.acquire()
        try:
            z = x+y; w = x-y
            print z*w
            time.sleep(1)
            if flag == 0:
                print "ABORTING"
                return
        finally:
            print " SINGLE run of thread executed"
            lock.release()
</code></pre>

<h1>test28.py</h1>

<pre><code>import time, threading

from test27 import Read

print "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"
</code></pre>

<p>The <code>Thread</code> class can be instantiated with the <code>target</code> argument. Then you just give it a function which should be raun in a new thread. It is a convenient way to start a simple thread, but for more control it is usualy easier to have a class inherited from <code>Thread</code>, which has additional member variables, like the <code>flag</code> for aborting.</p>

<p>For example:</p>

<pre><code>import time
import threading

class MyThread(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 = False

    def run(self):
        while not self._stop_requested:
            z = self.x + self.y
            w = self.x - self.y
            print (z * w)
            time.sleep(1)

    def stop(self, timeout=None):
        self._stop_requested = True
        self.join(timeout)
</code></pre>

<p>Then, to start the thread, call <code>start()</code> and then to stop it call <code>stop()</code>:</p>

<pre><code>&gt;&gt;&gt; def run_thread_for_5_seconds():
...     t = MyThread(3, 4)
...     t.start()
...     time.sleep(5)
...     t.stop()
...
&gt;&gt;&gt; run_thread_for_5_seconds()
-7
-7
-7
-7
-7
&gt;&gt;&gt;
</code></pre>

python multithreading time