Reputation: 83
I am writing a python library that will be used on unix/windows. I am facing an issue with terminating t1
thread. I have tried setting it to daemon
thread but because the library is sometimes used in IDE/applications, t1
thread won't close until the whole application closes - which is not desired. Now, I am trying to change it to non-daemon thread and handle the termination manually.
def threadclick(id, stop):
while(True):
//do things repetitively //
if stop():
break
def main():
global stop_thread
stop_thread = False
port_string1 = port_string
t1 = threading.Thread(target=threadclick, args=(id, lambda : stop_thread))
t1.start()
I need to be able to close it by calling this function:
def close_thread():
global stop_thread
stop_thread = True
t1.join
of course it is giving me t1 is undefined error but I am not sure how to declare it globally.
Upvotes: 0
Views: 32
Reputation: 20450
Passig a constant value read from a simple scalar, rather than passing a reference, is a concern, as you wouldn't want to keep re-reading an unchanging value. A dict will be convenient.
The function you were using seemed a little on the complex side.
Also, you'd probably be better off passing around a reference, rather than relying on a global.
Use this:
def threadclick(id, status):
while not status['stop']:
do_things()
status = dict(stop=False)
def main():
status['stop'] = False
t1 = threading.Thread(target=threadclick, args=(id, status))
t1.start()
wait_for_things_to_happen()
close_thread(t1, status)
def close_thread(t1, status):
status['stop'] = True
t1.join()
Upvotes: 1