亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在一段時間后停止運行我的線程?

如何在一段時間后停止運行我的線程?

青春有我 2021-08-24 17:03:47
我需要在一段時間后停止運行我的線程,在這個例子中我只放了 120 秒。我嘗試使用這種方法是行不通的。from threading import Threadfrom Queue import Queueimport osimport timetimeout = 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 回答

?
慕姐4208626

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-

那里發生了什么 - 您正在啟動兩個線程,每個線程在系統中啟動單獨的進程。在上述線程啟動后,您返回主線程,分配一個“鎖”并等待此鎖發出信號或超時。在這種特殊情況下,沒有人發出鎖定信號,因此完成應用程序的唯一機會是等待超時發生。我會擴展您的應用程序,它會在每個線程函數中發出鎖定信號,因此只有當兩個線程函數都終止時,我們才能終止主線程。但這不是你問題的一部分,所以我假設你可以不發信號就離開。


查看完整回答
反對 回復 2021-08-24
  • 1 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號