簡體   English   中英

Python3 並行運行多個函數

[英]Python3 run multiple functions in parallel

def send_to_analyser(pkt):

    if OSPF_LSUpd in pkt:
        global pkt_num
        pkt_num_field = struct.pack('h', pkt_num % 65535)
        pkt_bytes = raw(pkt)
        s.sendto(pkt_num_field + pkt_bytes, ('127.0.0.1', 9527))


def packet_capture():
    print('[+] Starting sniffing the Link State Update packets of the target network...')
    pkts = sniff(filter="proto ospf", iface=veth_list, prn=send_to_analyser)


def test_thread():
    for i in range(1,10):
        print("test thread " + str(i))
        sleep(3)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

以上是我的代碼的簡化版本,我想並行運行 packet_capture() 和 test_thread(),我該怎么做?

對於這樣的簡單情況,您可能需要查看threading包,以生成具有所需功能的新Thread

import threading

# the names are not required but can be useful for debugging if needed
# if the targets have arguments you can specify with the 'arg' argument
t_capture = threading.Thread(target=packet_capture, name="capture")
t_test = threading.Thread(target=test_thread, name="test")

# start the threads
t_capture.start()
t_thread.start()

# wait for them to finish with optional timeout in seconds
t_capture.join()
t_test.join()

你可以只使用線程。 這是一個例子

import threading
import time

threadRunning = True

def test_thread1():
  while threadRunning:
    for i in range(1,5):
      print("test thread 1: " + str(i))
      time.sleep(0.5)

def test_thread2():
  while threadRunning:
    for i in range(1,5):
      print("test thread 2: " + str(i))
      time.sleep(0.33)


x = threading.Thread(target=test_thread1, args=())
x.start()
y = threading.Thread(target=test_thread2)
y.start()
time.sleep(10)
threadRunning = False
print("Stop it!")
time.sleep(2)

暫無
暫無

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

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