Python3 run multiple functions in parallel

Viewed 101
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)

Above is the reduced version of my code, I wanna run packet_capture() and test_thread() in parallel, how could I do that ?

2 Answers

For a simple case like this, you would whant to look at the threading package, to generate new Thread with the desired functions.

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()

You could just use threading. Here is an example

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)
Related