Python 官方文档:入门教程 => 点击学习
python的condition和阻塞队列Queue 条件(Condition) 条件同步机制是指:一个线程等待特定条件,而另一个线程发出特定条件满足的信号。 解释条件同步机制的一个很好的例子就是生产者/消费者(producer/
#!/usr/bin/env Python
# -*- coding: utf-8 -*-
# @Time : 2017/7/25 9:40
# @File : produ.py
import random
import threading
import time
#生产者
class Producer(threading.Thread):
def __init__(self,integers,condition,name):
"""
构造器
@:param integers 整数列表
@:param condition 条件同步对象
@:param name 线程名字
"""
threading.Thread.__init__(self)
self.integers = integers
self.condition = condition
self.name = name
def run(self):
"""
向队列中随机添加数字
:return:
"""
while True:
integer = random.randint(0,300)
self.condition.acquire() #获取锁
print '锁被',self.name,'拿了'
self.integers.append(integer) #加入列表
print integer,'被',self.name,'加入列表'
print '锁 被',self.name,'唤醒'
self.condition.notify()
print '锁被',self.name,'释放'
self.condition.release()
time.sleep(1)
#消费者
class Consumer(threading.Thread):
def __init__(self,integers,condition,name):
threading.Thread.__init__(self)
self.integers = integers
self.condition = condition
self.name = name
def run(self):
while True:
self.condition.acquire()
print '锁被',self.name,'拿了'
while True:
if self.integers:
integer = self.integers.pop()
print integer,'从列表中被',self.name,'移除'
break
print self.name,'等待'
self.condition.wait()
print '锁被',self.name,'释放'
self.condition.release()
def main():
integers = []
condition = threading.Condition()
consumer = Consumer(integers,condition,'消费者')
producer = Producer(integers,condition,'生产者')
producer.start()
consumer.start()
producer.join()
consumer.join()
if __name__ == '__main__':
main()
main()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/7/25 10:10
# @File : que.py
#生产者消费者,阻塞队列实现
import random
from Queue import Queue
import threading
import time
class Producer(threading.Thread):
"""
@:param queue 阻塞队列
@:param name 线程名字
"""
def __init__(self,queue,name):
threading.Thread.__init__(self)
self.queue = queue
self.name = name
def run(self):
while True:
integer = random.randint(0,350)
self.queue.put(integer)
print self.name,'将',integer,'加入队列'
time.sleep(6)
class Consumer(threading.Thread):
def __init__(self,queue,name):
threading.Thread.__init__(self)
self.queue = queue
self.name = name
def run(self):
while True:
integer = self.queue.get()
print self.name,'将',integer,'从队列中移除'
self.queue.task_done()
def main():
queue = Queue(32)
consumer = Consumer(queue,'消费者')
producer = Producer(queue,'生产者')
producer.start()
consumer.start()
if __name__ == '__main__':
main()
main()
--结束END--
本文标题: Python的condition和阻塞队
本文链接: https://www.lsjlt.com/news/188846.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0