[英]How to stop all threads on KeyboardInterupt with Python's workerpool
[英]How to stop ALL threads in Python?
我无法理解如何同时停止所有线程。
我有一个这样的代码,它从文件中读取行并启动许多线程。
是否可以一次停止所有线程?
import threading
import time
def doit(arg):
t = threading.currentThread()
while getattr(t, "do_run", True):
print ("working on %s" % arg)
time.sleep(10)
print("Stopping as you wish.")
def main():
with open('C:\\Users\\Admin\\Desktop\\dump\\domains.txt') as file:
for line in file:
print(line.rstrip())
t = threading.Thread(target=doit, args=(line.rstrip(), ))
t.start()
t.do_run = False
if __name__ == "__main__":
main()
全局变量在所有线程之间共享,因此您可以使用它:
run = True
def thread_func():
global run
while run:
# do stuff
sleep(10)
for i in range(10):
Thread(target=thread_func).start()
sleep(10)
run = False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.