在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()
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()
相关文章推荐
- 在python中实现生产者和消费者的例子(五):使用threading模块和全局变量
- 在python中实现生产者和消费者的例子(一):使用multiprocessing和pipe()
- Python 3 实现定义跨模块的全局变量和使用
- 在python中实现生产者和消费者的例子(三):使用fork和pipe
- Python 3 实现定义跨模块的全局变量和使用
- 在python中实现生产者和消费者的例子(二):使用multiprocessing和queue
- python3 动态模块导入与全局变量使用
- python使用queue队列实现生产者消费者
- Python多线程 - 使用_thread模块实现多线程
- python使用threading.condition实现生产者消费者
- Python 中模块间全局变量的使用上的注意
- python3 - 声明全局变量并在不同模块中的使用.
- python使用队列实现生产者消费者
- python中线程的使用以及生产者和消费者的实现
- 使用Python实现生产者消费者问题
- 使用Python实现生产者消费者问题
- python学习笔记之使用threading模块实现多线程(转)
- 10 Python 函数内使用全局变量注意项
- 11.python并发入门(part8 基于线程队列实现生产者消费者模型)
- 多线程实现消费者生产者的例子