Reputation: 696
Hello I would like to stop a thread that is running but I have to stop it from a function Here is my code
import os
import time
import threading
def run():
while True:
print("ok")
time.sleep(1)
global stop
if stop:
print("stopped")
break
def stopper():
stop = True
t1.join()
print("done")
stop = False
t1 = threading.Thread(target=run)
t1.start()
time.sleep(4)
stopper()
I am forced to stop it from the stopper function and can't do it like that even if in this case it would work,My objective is to activate the stopper function from a tkinter button
time.sleep(4)
stop = True
t1.join()
print("done")
Upvotes: 0
Views: 955
Reputation: 1548
how is with mp.Manager and ctypes, without global declaration
import multiprocessing as mp
import ctypes
import os
import time
import threading
def tunnel_signal():
manager = mp.Manager()
return manager.Value(ctypes.c_char_p, False)
def run(stop_signal):
while True:
print("ok")
if stop_signal.value:
break
def stopper():
stop = True
t1.join()
print("done")
stop_thread = tunnel_signal()
t1 = threading.Thread(target=run, args=(signal,))
t1.start()
time.sleep(4)
stop_thread.value = True
Upvotes: 0
Reputation: 5180
You're missing a global
declaration in your stopper
function.
def stopper():
global stop
stop = True
t1.join()
print("done")
Will fix the issue.
Upvotes: 1
Reputation: 5930
You have to put
global stop
into your stopper()
function as well. Otherwise the function will not set the global stop
but just a local variable with that name.
Upvotes: 1