日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

11.python并发入门(part8 基于线程队列实现生产者消费者模型)

發布時間:2025/6/15 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 11.python并发入门(part8 基于线程队列实现生产者消费者模型) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、什么是生產者消費者模型?

生產者就是生產數據的線程,消費者指的就是消費數據的線程。

在多線程開發過程中,生產者的速度比消費者的速度快,那么生產者就必須等待消費者把數據處理完,生產者才會產生新的數據,相對的,如果消費者處理數據的速度大于生產者,那么消費者就必須等待生產者。

為了解決這種問題,就有了生產者消費者模型。


生產者與消費者模型,是通過一個容器,來解決生產者和消費者之間的耦合性問題,生產者和消費者之間并不會直接通信,這樣生產者就無需等待消費者處理完數據,生產者可以直接把數據扔給隊列,這個時候消費者也無需找生產者要數據,直接去隊列中取數據,這個隊列,起到的就是一個緩沖區的作用,具有平衡生產者和消費者的處理能力。


二、基于隊列的生產者消費者模型的示例。

ver1:

#!/usr/local/bin/python2.7

# -*- coding:utf-8 -*-

import time

import random

import Queue

import threading

q1 = Queue.Queue()

def producer(name):

? ? count = 0

? ? while count < 10:

? ? ? ? print ?"making..."

? ? ? ? time.sleep(random.randrange(3))

? ? ? ? q1.put(count)

? ? ? ? print "procucer %s has produced %s baozi...." %(name,count)

? ? ? ? count += 1

? ? ? ? print "ok!"

def consumer(name):

? ? count = 0

? ? while count < 10:

? ? ? ? time.sleep(random.randrange(4))

? ? ? ? if not q1.empty():

? ? ? ? ? ? data = q1.get()

? ? ? ? ? ? print data

? ? ? ? ? ? print '\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data)

? ? ? ? else:

? ? ? ? ? ? print "not fond baozi"

? ? ? ? count += 1

if __name__ == '__main__':

? ? p1 = threading.Thread(target=producer,args=('A',))

? ? c1 = threading.Thread(target=consumer,args=('B',))

? ? p1.start()

? ? c1.start()


ver2:

#!/usr/local/bin/python2.7

# -*- coding:utf-8 -*-

import time

import random

import Queue

import threading

q1 = Queue.Queue()

def producer(name):

? ? count = 0

? ? while count < 10:

? ? ? ? print ?"making..."

? ? ? ? time.sleep(random.randrange(3))

? ? ? ? q1.put(count)

? ? ? ? print "procucer %s has produced %s baozi...." %(name,count)

? ? ? ? count += 1

? ? ? ? q1.task_done() ?#給隊列發個信號,告訴隊列put完畢

? ? ? ? #q1.join()

? ? ? ? print "ok!"

def consumer(name):

? ? count = 0

? ? while count < 10:

? ? ? ? q1.join() ##監聽生產者發送給隊列的信號

? ? ? ? time.sleep(random.randrange(4))

? ? ? ?# if not q1.empty():

? ? ? ? data = q1.get()

? ? ? ? #q1.task_done()

? ? ? ? print data

? ? ? ? print '\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data)

? ? ? ? #else:

? ? ? ? #print "not fond baozi"

? ? ? ? count += 1

if __name__ == '__main__':

? ? p1 = threading.Thread(target=producer,args=('A',))

? ? c1 = threading.Thread(target=consumer,args=('B',))

? ? c2 = threading.Thread(target=consumer,args=('C',))

? ? c3 = threading.Thread(target=consumer,args=('D',))

? ? p1.start()

? ? c1.start()

? ? c2.start()

? ? c3.start()


轉載于:https://blog.51cto.com/suhaozhi/1925548

總結

以上是生活随笔為你收集整理的11.python并发入门(part8 基于线程队列实现生产者消费者模型)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。