有没有一种方法可以阻止Python包括代码中的所有线程?

时间:2020-09-25 07:27:34

标签: python multithreading

我试图停止我自动编写的脚本,但是找不到停止线程和主要代码的方法。

import time
import threading
import sys

def thread():
    while True:
        print('hi')
        time.sleep(2)
        
t1 = threading.Thread(target=thread)
t1.start()

print('using sys.exit() in 5...')
time.sleep(1)
print('4')
time.sleep(1)
print('3')
time.sleep(1)
print('2')
time.sleep(1)
print('1')
time.sleep(1)
sys.exit()

这是一个伪代码^。我不是python的专家,我只知道基本知识。有没有办法,如果有,怎么办?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用全局变量来停止线程:

import threading 
import time 

def thread(): 
    while True: 
        print('thread running') 
        global stop_threads 
        if stop_threads: 
            break

stop_threads = False
t1 = threading.Thread(target=thread) 
t1.start() 
time.sleep(1) 
stop_threads = True
t1.join() 
print('thread killed') 

here中找到了更多根据情况停止线程的方法。

相关问题