gpt4 book ai didi

python - 试验 python 线程,如何停止线程

转载 作者:行者123 更新时间:2023-11-28 21:23:55 27 4
gpt4 key购买 nike

正在观看 David beazley 的( http://www.dabeaz.com ) video about python threads ,我正在尝试线程的东西

def countdown(n):
while n > 0:
if not n % 100000:
print n
n -= 1

>> from threading import Thread
>> t1=Thread(target=countdown,args=(10000000,))
>> t1.start();t1.join()
>>Ctrl-C

这给了

>>10000000
9900000
9800000
9700000
9600000
Ctrl-C9500000
9400000
...
400000
300000
200000
100000
----------
KeyboardInterrupt :
...

现在我试图找到线程的状态

>>t1.isAlive()
>>False

所以,我又尝试运行线程,结果报错

>>t1.start();t1.join()
--------------
RuntimeError: thread already started

为什么会这样?有没有办法停止线程?

最佳答案

在您使用的线程库中,线程的给定实例只能启动和停止一次,此后不能再次启动。您收到的错误消息是因为您试图在线程停止后启动它,所以您确实成功地停止了它。要“再次启动线程”,您必须实例化一个全新的线程并启动它。

关于python - 试验 python 线程,如何停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16805954/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com