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

来源:互联网 发布:淘宝来客提醒软件违规 编辑:程序博客网 时间:2024/05/22 10:26

本文介绍如何用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()
原创粉丝点击