簡體   English   中英

為什么 function 完成后我的線程沒有停止?

[英]Why my thread doesn't stop after function finished?

所以我寫了這個腳本,它計算某個端口上的收入數據包,如果有很多數據包腳本必須做一些事情。 在收到第一個數據包時,必須啟動計時器,如果計時器達到 60 秒,則數據包計數應重新從 0 開始。 它有效,但僅適用於第一次計時器調用,無論如何,如果腳本必須再次啟動計時器,我會收到錯誤消息:

raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once"`

很明顯,這個線程仍在運行,但我不明白為什么。 我的意思是,如果定時器達到 60 秒,定時器循環結束,function 也應該結束,所以我可以再次使用定時器嗎? 顯然我在這里不明白,你們能解釋一下嗎? 感謝您的回答我的代碼:

from scapy.all import *
from threading import Thread
import time
global count
count = 0

def timer():
    global count
    i = 0
    while i < 60:
        if count > 0:
            time.sleep(1)
            i = i + 1
            print(str(count))
        else:
            print("count is 0, timer turning off...")
            break
    else:
        count = 0
        print("60 seconds, timer is off")

background_thread = Thread(target=timer)

def pkt_callback(pkt):
    global count
    packet_limit = 10

    if pkt.haslayer(UDP) and pkt.getlayer(UDP).dport == 5160 and pkt.haslayer(Raw):
        raw = pkt.getlayer(Raw).load
        s = str(raw)

        if 'REGISTER' in s:
            count += 1
            print(count)

        if count == 1:
            if background_thread.is_alive() is False:
                background_thread.start()
                print("Register packet detected, timer is on")

        if count >= packet_limit:
            print("PACKETLIMIT reached, do smth")
            count = 0

        sniff(iface='ens160', filter="", prn=pkt_callback)

我認為您必須使用 return function 不會中斷,並且無論哪種方式您只使用過一次,您也可以稍微更改您的代碼,試試這個:

def timer():
       global count
       i = 0
       while i < 60:
           if count != 0:
                time.sleep(1)
                i += 1
                print(str(count))
           else:
                return "count is 0, timer turning off..."
       else:
           count = 0
           return "60 seconds, timer is off"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM