python 生产者消费者线程模型

python 多线程生产者消费者模型:

一个生产者多个消费者

The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the threading module.

Queue模块实现了多生产者、多消费者的队列,它在多线程编程中多线程的数据安全交换尤其有用,在模块中Queue类实现了所需的锁原语。在python中依赖于可用的多线程支持。

在本例中原本是使用条件变量来同步生产者消费者之间的队列信息,结果出问题了,查看文档后说Since the Queue has a Condition and that condition has its Lock we don‘t need to bother about Condition and Lock,翻译过来就是:因为队列有自己的条件对象,该对象有它自己的锁,我们不必担心条件对象和锁之间的处理。下面是处理代码

import logging

from threading import Thread, Condition, Lock

from Queue import Queue

from time import sleep

logger = logging.getLogger(‘mglottery.log‘)

sleep_time = 5

MAX_LENGTH = 16

THREAD_COUNT = 4

queue = Queue(MAX_LENGTH)

class ProducerThread(Thread):

def __init__(self, name="producer"):

print name

super(ProducerThread, self).__init__(name=name)

def add_task(self, start, end, poison=False):

for index in xrange(start, end):

goods = "can %d" % index if poison is False else None

queue.put(goods)

print ‘product one thing‘

def run(self):

global queue

while 1:

self.add_task(0, 100)

#send poison pill

self.add_task(0, THREAD_COUNT, True)

break

class ConsumerThread(Thread):

def __init__(self, name):

print name

super(ConsumerThread, self).__init__(name=name)

def run(self):

global queue

times = 0

while True:

goods = queue.get()

if goods is None:

print "consumer receive a poison pill, thread will exit"

break

else:

print ‘thread %s get job, queue size:%d ,goods:%s‘ % (self.getName(), queue.qsize(), goods)

if __name__=="__main__":

producer = ProducerThread(name="Can producer")

consumers = [ConsumerThread("Can consumer %d"%i) for i in range(THREAD_COUNT)]

producer.start()

for consumer in consumers:

consumer.start()

for consumer in consumers:

consumer.join()

producer.join()

时间: 2024-08-10 23:17:30

python 生产者消费者线程模型的相关文章

多线程--生产者/消费者线程模型

//程序演进1 //thread loop,忙等Busy wait //不断的检查是不是该做什么事情了:为了减少CPU占用,sleep睡眠一会 //while (1) //{ // do_something(); // sleep(time); //} //程序演进2 //while (1) //{ // read_form_intput(); // do_something(); //} //程序员演进3,消息模型 //while (waitForMsg) //{ // if (isQuitM

【java】生产者——消费者 线程模型

下面的4个文件体现了多线程的知识,以及线程同步(synchronized)的使用.其PopThread类对应消费者,PushThread类对应生产者,SafeStack对应存放资源的仓库.下面的TestSafeStack创建了1个生产者对象,1个存放资源的仓库对象,2个消费者对象. 消费者类: 1 /* 2 * 通过实现Runnable接口实现线程 3 */ 4 public class PushThread implements Runnable 5 { 6 /* 7 * 创建一个SafeSt

wait和notify实现的生产者消费者线程交互

public class ProductTest { public static void main(String args[]) { Repertory repertory=new Repertory(); new Thread(new Producer(repertory)).start(); new Thread(new Consumer(repertory)).start(); } } class Repertory{ private int product=0; public sync

使用Win32 API实现生产者消费者线程同步

使用win32 API创建线程,创建信号量用于线程的同步 创建信号量 语法例如以下 HANDLE semophore; semophore = CreateSemaphore(lpSemaphoreAttributes, lInitialCount, lMaximumCount, lpName); CreateSemophore函数的原型例如以下: HANDLE WINAPI CreateSemaphore( _In_opt_ LPSECURITY_ATTRIBUTES lpSemaphoreA

Python生产者消费者模型

用多线程和队列来实现生产者消费者模型 # -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import threading import queue import time q = queue.Queue() def Producer(name): count = 1 while True: q.put("面包%s" %count) print("[%s]做了[%s]个面包" %(name,cou

生产者消费者线程同步

生产者与消费者模式简单介绍: 生产者线程生产物品,然后将物品放置在一个空缓冲区中供消费者线程消费.消费者线程从缓冲区中获得物品,然后释放缓冲区.当生产者线程生产物品时,如果没有空缓冲区可用,那么生产者线程必须等待消费者线程释放出一个空缓冲区.当消费者线程消费物品时,如果没有满的缓冲区,那么消费者线程将被阻塞,直到新 public class ProduceConsumer { public static void main(String[] args) { SyncStack ss = new

python 生产者消费者模型

1 import queue 2 import threading 3 4 q = queue.Queue(10) 5 def product(i): 6 print('put:'+ str(i)) 7 q.put(i) 8 9 def customer(i): 10 msg = q.get() 11 print(msg) 12 13 for i in range(12): 14 t = threading.Thread(target=product,args=(i,)) 15 t.start(

python基础 信号量 semaphore evevt 线程queue 生产者消费者模型

线程锁相当于同时只能有一个线程申请锁,有的场景无数据修改互斥要求可以同时让多个线程同时运行,且需要限制并发线程数量时可以使用信号量 1 import threading, time, queue 2 3 def test(name): 4 semaphore.acquire() #获取信号量锁 5 print('my name is %s' %name) 6 time.sleep(1) 7 semaphore.release() #释放信号量锁 8 9 semaphore = threading

Java线程:并发协作-生产者消费者模型

对于多线程程序来说,不管任何编程语言,生产者消费者模型都是最经典的. 实际上,准确的说应该是"生产者-消费者-仓储"模型,离开了仓储,生产者消费者模型就显得没有说服力了. 对于此模型,应该明确以下几点: 生产者仅仅在仓储未满时候生产,仓满则停止生产. 消费者仅仅在仓储有产品时候才能消费,仓空则等待. 当消费者发现仓储没有产品的时候会通知生产者生产. 生产者在生产出可消费产品时候,应该通知消费者去消费. 此模型将要结合java.lang.Object的wait与notify,notify