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>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 <code>threading.Event</code>. Also you cannot access local variable <code>flag</code> 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.</p>

<pre><code>from threading import Event
flag = Event()

def Read(x,y):
    global flag
    flag.clear()
    ...
    if flag.is_set():
        return
</code></pre>

<p>main thread:</p>

<pre><code>sleep(5)
flag.set()
</code></pre>

<p>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.  </p>

python multithreading time