在python中实现生产者和消费者的例子(四):使用thread模块和全局变量

本文详细探讨了如何利用Python的thread模块以及全局变量来构建一个典型的生产者-消费者问题解决方案。通过实例代码,阐述了如何在多线程环境下协调生产者和消费者的同步操作。
摘要由CSDN通过智能技术生成

本文介绍如何用thread模块实现生产者和消费者的例子

import thread
import time
import random

c=0
lock=thread.allocate_lock()

def producer(no):
    global c
    while True:
        if c<=100:
            time.sleep(random.randint(1,3))
            lock.acquire()
            c=c+1
            lock.release()
            print 'No %d producer-- %d' %(no,c)
        else:
            time.sleep(random.randint(1,3))
        
def consumer(no):
    global c
    while True:
        if c>0:
            time.sleep(random.randint(1,3))
            lock.acquire()
            c=c-1
            lock.release() 
            print 'No %d consumer--%d' %(no,c)            
        else:
            time.sleep(random.randint(1,3))
  
def center():
    #(1,)是为了表示其是元组,若写成(1)则为整型
    thread.start_new_thread(producer,(1,))
    thread.start_new_thread(producer,(2,))    
    thread.start_new_thread(producer,(3,))       
    thread.start_new_thread(consumer,(4,))     
    thread.start_new_thread(consumer,(5,))
    thread.start_new_thread(consumer,(6,))
    time.sleep(1000)
    
if __name__=='__main__':
    center()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值