您的位置:首页 > 编程语言 > Python开发

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

2013-09-04 13:32 976 查看
本文介绍如何用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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: