本文介绍如何用thread模块实现生产者和消费者的例子
import threadimport 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()