我無法理解如何同時停止所有執行緒。
我有一個這樣的代碼,它從檔案中讀取行并啟動許多執行緒。
是否可以一次停止所有執行緒?
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()
uj5u.com熱心網友回復:
全域變數在所有執行緒之間共享,因此您可以使用它:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/349074.html
