1 回答

TA貢獻1852條經驗 獲得超7個贊
我認為這就是您要實現的目標:
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-
那里發生了什么 - 您正在啟動兩個線程,每個線程在系統中啟動單獨的進程。在上述線程啟動后,您返回主線程,分配一個“鎖”并等待此鎖發出信號或超時。在這種特殊情況下,沒有人發出鎖定信號,因此完成應用程序的唯一機會是等待超時發生。我會擴展您的應用程序,它會在每個線程函數中發出鎖定信號,因此只有當兩個線程函數都終止時,我們才能終止主線程。但這不是你問題的一部分,所以我假設你可以不發信號就離開。
添加回答
舉報