我试图在函数中使用线程函数。但我的终端说全局名称'thread1'没有定义?有没有可能实现它的方法?
我的代码是这样的:
import time
import threading
count = 0
class Screen(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.thread_stop = False
def run(self):
while not self.thread_stop:
main()
def stop(self):
self.thread_stop = True
def test():
thread1 = Screen()
thread1.start()
def main():
global thread1,count
while True:
time.sleep(1)
count += 1
if count >=3:
thread1.stop()
print "Stop!"
break
test()
答案 0 :(得分:0)
您错过了thread1
函数中test
的全局声明:
def test():
global thread1
...
否则,python会将thread1
中的test
视为局部变量,因此在主thread1
中不会将其视为已初始化。
我建议采用不同的方法(我发现更清晰,更安全):
import time
import threading
count = 0
class Screen(threading.Thread):
def __init__(self, count):
threading.Thread.__init__(self)
self.count = count
def do_something(self):
while True:
time.sleep(1)
self.count += 1
if self.count >=3:
print "Stop!"
break
def run(self):
self.do_something()
def test():
thread1 = Screen(count)
thread1.start()
test()
答案 1 :(得分:0)
最好使用不同的逻辑:
from threading import Thread, Event
import time
evt_stop = Event()
def activity():
count = 0
while not evt_stop.is_set():
time.sleep(1)
count += 1
if count >=3:
evt_stop.set()
print "Stop!"
break
thread = Thread(target=activity)
thread.start()
thread.join()