python thread 生產者消費者模式

2021-09-02 14:12:36 字數 686 閱讀 2953

from queue import queue

import time

import threading

#生產者消費者模式是執行緒間通訊的一種應用

#在使用資料結構的時候確定是否是執行緒安全,queue本身是執行緒安全的

#list() dict({}) 都不是執行緒安全的

def set_value(q):

index = 0

while true:

q.put(index)

index += 1

q.put(index)

index += 1

time.sleep(2)

def get_value(q):

while true:

print("消費者獲取資料",q.get()) #如果隊列為空,get()方法會sleep,直到佇列有資料

def main():

q = queue(8)

t1 = threading.thread(target=set_value,args=[q])

t2 = threading.thread(target=get_value,args=[q])

t1.start()

t2.start()

if __name__ == '__main__':

main()

生產者消費者 生產者與消費者模式

一 什麼是生產者與消費者模式 其實生產者與消費者模式就是乙個多執行緒併發協作的模式,在這個模式中呢,一部分執行緒被用於去生產資料,另一部分執行緒去處理資料,於是便有了形象的生產者與消費者了。而為了更好的優化生產者與消費者的關係,便設立乙個緩衝區,也就相當於乙個資料倉儲,當生產者生產資料時鎖住倉庫,不...

多生產者 多做「生產者」,少做「消費者」

生產者 vs 消費者 哪個更好?消費者 定義非常廣泛,購買一件物品 進行一次消費的人都是消費者 更深一層的含義就是 消費 了你的金錢 時間 精力,比如刷抖音,花費了你的時間和精力,單方面地接受資訊 向內汲取 向外消耗時間或金錢,那你就是 消費者 生產者 生產 製造 創作了某個物品 作品,別人消費你的...

生產者消費者

using system using system.collections.generic using system.threading namespace gmservice foreach thread thread in producers q.exit console.read public...