code
fromqueue import queue
from
threading import thread
# 用來表示終止的特殊物件
_sentinel = object
()# a thread that produces data
def producer(out_q):
for i in range(10
): print("生產
")out_q.put(i)
out_q.put(_sentinel)
# a thread that consumes data
def consumer(in_q):
while
true:
data = in_q.get
()
if data is
_sentinel:
in_q.put(_sentinel)
break
else
: print("消費
", data)
# create the shared queue and launch both threads
q =queue()
t1 = thread(target=consumer, args=(q,))
t2 = thread(target=producer, args=(q,))
t1.start()
t2.start()
輸出
macname@macdembp ~ % python -u "/users/macname/desktop/test.py"生產
生產消費 0生產
生產生產
消費 1
消費 2
消費 3
生產生產
生產生產
生產消費
4消費
5消費
6消費
7消費
8消費
9macname@macdembp ~ %
5 12 生產者和消費者
一 生產者和消費者之間的關係 1 生產者將生產出來的資訊不斷存入乙個區域內,消費者將資訊從該區域內不斷讀取出來 生產者錄入資訊 消費者讀取資訊 例 電影票 public class movie public void setname string name public string getinfo...
6 1 生產者 消費者問題
在多執行緒程式中,執行緒之間通常存在分工。在一種常見模式中,一些執行緒是生產者,一些是消費者。需要強制執行幾個同步約束才能使此系統正常工作 在緩衝區中新增或刪除專案時,緩衝區處於不一致狀態。因此,執行緒必須具有對緩衝區的獨佔訪問許可權。如果消費者執行緒在緩衝區為空時到達,則會阻塞,直到生產者新增新專...
26 生產者消費者模型
一 ipc 空間復用 中記憶體隔離開了多個程序直接不能直接互動 ipc指的就是程序間通訊 幾種方式 1 建立乙個共享檔案 缺點 效率較低 優點 理論上交換的資料量可以非常大 適用於 互動不頻繁,且資料量較大的情況 2 共享記憶體 缺點 資料量不大 優點 效率高 適用於 互動頻繁,但是資料量小 3 管...