更新時(shí)間:2024-03-05 來(lái)源:黑馬程序員 瀏覽量:
在Python中,線(xiàn)程之間可以使用多種方式進(jìn)行通信。以下是一些常見(jiàn)的通信方式及其示例代碼:
1.共享變量:
多個(gè)線(xiàn)程可以通過(guò)共享變量來(lái)進(jìn)行通信。但是需要注意線(xiàn)程安全的問(wèn)題,可以使用鎖(Lock)或者信號(hào)量(Semaphore)來(lái)保護(hù)共享資源的訪(fǎng)問(wèn)。
import threading shared_variable = 0 lock = threading.Lock() def thread_func(): global shared_variable for _ in range(1000000): lock.acquire() shared_variable += 1 lock.release() threads = [] for _ in range(10): t = threading.Thread(target=thread_func) threads.append(t) t.start() for t in threads: t.join() print("Final value of shared_variable:", shared_variable)
2.隊(duì)列:
可以使用隊(duì)列來(lái)實(shí)現(xiàn)線(xiàn)程之間的安全通信。Python中的Queue模塊提供了多種隊(duì)列實(shí)現(xiàn),如Queue、LifoQueue和PriorityQueue。
import threading import queue q = queue.Queue() def producer(): for i in range(5): q.put(i) print("Produced", i) def consumer(): while True: item = q.get() if item is None: break print("Consumed", item) q.task_done() t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t1.start() t2.start() t1.join() q.put(None) t2.join()
3.事件:
線(xiàn)程可以等待事件的觸發(fā)或者清除。使用threading.Event類(lèi)可以實(shí)現(xiàn)。
import threading event = threading.Event() def waiter(): print("Waiting for event") event.wait() print("Event occurred") def setter(): print("Event set") event.set() t1 = threading.Thread(target=waiter) t2 = threading.Thread(target=setter) t1.start() t2.start() t1.join() t2.join()
4.條件變量:
使用threading.Condition類(lèi)可以實(shí)現(xiàn)多個(gè)線(xiàn)程之間的復(fù)雜通信。
import threading import time condition = threading.Condition() item = None def consumer(): global item with condition: condition.wait_for(lambda: item is not None) print("Consumed", item) item = None condition.notify() def producer(): global item with condition: time.sleep(1) item = "test" print("Produced", item) condition.notify() t1 = threading.Thread(target=consumer) t2 = threading.Thread(target=producer) t1.start() t2.start() t1.join() t2.join()
這些是一些常見(jiàn)的線(xiàn)程間通信方式。在選擇使用哪種方式時(shí),應(yīng)根據(jù)具體的需求和情況來(lái)決定。