如何在Python上中断线程

时间:2018-04-02 14:45:36

标签: python multithreading interrupt python-multithreading

是否有可能是一个python线程的中断,例如我希望在30秒后中断该线程。

import threading
import time

def waiting():
    print("thread is started")
    time.sleep(60)
    print("thread is finished")

thread = threading.Thread(target=waiting, name="thread_1")
thread.start()

1 个答案:

答案 0 :(得分:-1)

我找到了解决方案,我正在使用多处理模块,解决方案示例:

from multiprocessing import Process
import time

def waiting():
    print("thread is started")
    time.sleep(60)
    print("thread is finished")


if __name__ == '__main__':
    p = Process(target=waiting)
    p.start()
    time.sleep(30)
    p.terminate()

过程开始并在30秒后终止。