有谁知道为什么运行此代码会导致脚本挂在线程中,除非我取消注释 print、sleep 或“if”条件,或者删除 try/ except?我的理解是这个线程不应该阻塞主线程。
import threading
import time # noqa
class Something:
def __init__(self):
self.thread = threading.Thread(target=self.thread_loop, daemon=True)
self.keep_looping = True
self.a = 0
def start_thread(self) -> None:
self.thread.start()
def stop_thread(self) -> None:
self.keep_looping = False
print('stop')
def thread_loop(self) -> None:
print('thread_loop')
while self.keep_looping:
try:
# print('loop')
# time.sleep(0.1)
self.a += 1
# if self.a == 'xxxx':
# print(self.a)
# time.sleep(0.1)
except Exception as err:
print(err)
blinky = Something()
print('start')
blinky.start_thread()
print('stop')
blinky.stop_thread()
print('done')
有谁知道为什么运行此代码会导致脚本挂在线程中......?
我没有看到你的脚本挂起。如果我未经修改地运行它,我会看到:
start
thread_loop
stop
stop
done
有点不清楚你希望在这里完成什么;对
start_thread()
的调用和对 stop_thread()
的调用之间的时间实际上为零,但由于 thread_loop()
实现了严格的 CPU 绑定循环,我们可以通过在末尾添加额外的 print
来显示 something正在发生你的代码:
blinky = Something()
print('start')
blinky.start_thread()
print('stop')
blinky.stop_thread()
print('done')
print(blinky.a)
根据上面的代码,我们看到:
start
thread_loop
stop
stop
done
159022
向我们展示
thread_loop
循环了 159,022 次(实际数量会根据您的 CPU 速度、系统中的 CPU 数量、运行的其他程序数量等而有所不同)。
有可能,在你的系统上,thread_loop
中的循环消耗了太多的CPU,以至于没有其他东西有时间运行......在这种情况下,任何显式休眠(例如
time.sleep()
)或参与的东西i/o(例如
print
语句)将让出对处理器的控制权,足以让另一个线程运行。当您的代码不
主要受CPU限制时,Python中的线程主要有用。由于全局解释器锁,Python 中的多个线程无法能够并行运行,从而导致了我在上一段中描述的情况。