python线程运行完会自动停止吗_python – 一段时间后如何停止运行我的线程?
我认为这是你想要实现的目标:
import threading
from queue import Queue
import os
import time
timeout = 120 # [seconds]
timeout_start = time.time()
def OpenWSN ():
print( "OpenWSN:")
os.system("echo -OpenWSN-")
def Wireshark():
print( "Wireshark:")
os.system("echo -Wireshark-")
def wrapper1(func, queue):
queue.put(func())
def wrapper2(func, queue):
queue.put(func())
q = Queue()
threading.Thread(target=wrapper1, args=(OpenWSN, q)).start()
threading.Thread(target=wrapper2, args=(Wireshark, q)).start()
cv = threading.Condition()
cv.acquire()
cv.wait( timeout )
print ("***************** End Simulation *************************")
print (" Simulation Time: {0}s".format( time.time() - timeout_start) )
os.system("echo -exit-")
这会产生以下输出:
C:\temp\StackExchange\StopRunningThread>python -B stop-running-thread.py
OpenWSN:
Wireshark:
-OpenWSN-
-Wireshark-
***************** End Simulation *************************
Simulation Time: 120.04460144042969s
-exit-
那里发生了什么 – 你正在启动两个线程,每个线程在系统中启动单独的进程.在启动所述线程之后,返回主线程,分配“锁定”并等待该锁定发出信号或发生超时.在这种特殊情况下,没有人发出锁定信号,因此完成应用程序的唯一机会是等到超时发生.我会扩展你的应用程序,它在每个线程函数中发出锁定信号,所以只有当两个线程函数都终止时我们才能终止主线程.但这不是你问题的一部分,所以我假设你可以离开而不发信号.
