溫馨提示×

python同步執(zhí)行代碼怎么實(shí)現(xiàn)

小億
104
2023-11-15 20:47:09
欄目: 編程語言

在Python中,可以使用多線程或多進(jìn)程來實(shí)現(xiàn)代碼的同步執(zhí)行。

  1. 使用多線程進(jìn)行同步執(zhí)行:
import threading

def task1():
    print("Task 1 started")
    # 同步執(zhí)行的代碼
    print("Task 1 completed")

def task2():
    print("Task 2 started")
    # 同步執(zhí)行的代碼
    print("Task 2 completed")

if __name__ == "__main__":
    thread1 = threading.Thread(target=task1)
    thread2 = threading.Thread(target=task2)
    
    thread1.start()
    thread2.start()
    
    thread1.join()
    thread2.join()

在這個例子中,我們創(chuàng)建了兩個線程,每個線程執(zhí)行一個任務(wù)。通過調(diào)用start()來啟動線程,然后通過調(diào)用join()來等待線程執(zhí)行完畢。

  1. 使用多進(jìn)程進(jìn)行同步執(zhí)行:
import multiprocessing

def task1():
    print("Task 1 started")
    # 同步執(zhí)行的代碼
    print("Task 1 completed")

def task2():
    print("Task 2 started")
    # 同步執(zhí)行的代碼
    print("Task 2 completed")

if __name__ == "__main__":
    process1 = multiprocessing.Process(target=task1)
    process2 = multiprocessing.Process(target=task2)
    
    process1.start()
    process2.start()
    
    process1.join()
    process2.join()

在這個例子中,我們創(chuàng)建了兩個進(jìn)程,每個進(jìn)程執(zhí)行一個任務(wù)。通過調(diào)用start()來啟動進(jìn)程,然后通過調(diào)用join()來等待進(jìn)程執(zhí)行完畢。

無論是使用多線程還是多進(jìn)程,都可以實(shí)現(xiàn)代碼的同步執(zhí)行。具體選擇使用哪種方式,取決于你的需求和代碼的特點(diǎn)。

0