Python的多執行緒

 

執行緒的基本範例

import threading
import time

def thread_taskA(threadName, delay):
    i = 0
    while i<5:
        i = i + 1
        time.sleep(delay)
        print(threadName + ':', i)

def thread_taskB(threadName, delay):
    i = 0
    while i<5:
        i = i + 1
        time.sleep(delay)
        print(threadName + ':', i)

def thread_taskC(threadName, delay):
    i = 0
    while i<5:
        i = i + 1
        time.sleep(delay)
        print(threadName + ':', i)

a = threading.Thread(target=thread_taskA, ('Thread-A', 0.5, ) )
b = threading.Thread(target=thread_taskB, ('Thread-B', 0.6, ) )
b = threading.Thread(target=thread_taskC, ('Thread-C', 0.5, ) )

a.start()
b.start()
c.start()

執行緒的同步控制

start()|啟動執行緒

join()|等待執行緒的執行完畢

is_alive()|執行緒是否已經啟動

import threading
import time

def thread_taskA(threadName, delay):
    i = 0
    while i<5:
        i = i + 1
        time.sleep(delay)
        print(threadName + ':', i)

def thread_taskB(threadName, delay):
    i = 0
    while i<5:
        i = i + 1
        time.sleep(delay)
        print(threadName + ':', i)

def thread_taskC(threadName, delay):
    i = 0
    while i<5:
        i = i + 1
        time.sleep(delay)
        print(threadName + ':', i)

a = threading.Thread(target=thread_taskA, ('Thread-A', 0.5, ) )
b = threading.Thread(target=thread_taskB, ('Thread-B', 0.6, ) )
b = threading.Thread(target=thread_taskC, ('Thread-C', 0.5, ) )

a.start()
b.start()
a.join()   # 等待 a 完成
b.join()   # 等待 b 完成
c.start()  # 在a,b完成後,c才開始啟動

Lock

Lock()|建立lock

acquire()|鎖定

release()|解除鎖定

import threading

lock = threading.Lock()         # 透過建立 Lock

lock.acquire()         # 鎖定
lock.release()         # 解除鎖定

Event

Event()|註冊一個事件

set()|觸發該事件

wait()|等待該事件被觸發

clear()|將該事件的狀態清除至未被觸發的狀態

# 註冊事件
event = threading.Event()   

# 觸發事件
event.set()

# 等待事件被觸發
event.wait()

# 觸發後將事件回歸原本狀態
event.clear()