一段时间后如何停止运行线程?

时间:2018-11-21 16:09:10

标签: python shell python-multithreading

一段时间后,我需要停止运行线程,在此示例中,我只花了120秒。我尝试通过使用此方法不起作用。

from threading import Thread
from Queue import Queue
import os
import time

timeout = 120   # [seconds]

timeout_start = time.time()

#while True :


def OpenWSN ():
    os.system("./toto")

def Wireshark():
    os.system(" tshark -i tun0 -T ek -w /home/ptl/PCAP_Brouillon/Sim_Run3rd.pcap > /dev/null ")


def wrapper1(func, queue):
    queue.put(func())

def wrapper2(func, queue):
    queue.put(func())


q = Queue()
Thread(target=wrapper1, args=(OpenWSN, q)).start()
Thread(target=wrapper2, args=(Wireshark,  q)).start()

#print (time.time())
print ("***************** End Simulation *************************")
os.system("quit")

1 个答案:

答案 0 :(得分:0)

我认为这是您要实现的目标:

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-

那里发生了什么-您正在启动两个线程,每个线程在系统中启动单独的进程。在启动了所述线程之后,您将返回主线程,分配一个“锁”,并等待直到发出此锁信号,否则发生超时。 在这种情况下,没有人会发出锁定信号,因此完成应用程序的唯一机会就是等待超时发生。 我将扩展您的应用程序,使其发出每个线程函数已锁定的信号,因此仅当两个线程函数都终止时,才能终止主线程。 但这不是您的问题的一部分,因此我认为您可以在没有信号的情况下离开。

相关问题