Last active
September 8, 2016 08:25
-
-
Save zhyq0826/0a95219e341de3975e79ec4bb68abe0c to your computer and use it in GitHub Desktop.
python 生产者消费者模式使用condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import time | |
import thread | |
from threading import Thread, Condition, Event, Lock, currentThread | |
from Queue import Queue | |
class ItemQ(object): | |
def __init__(self): | |
self.count = 0 | |
def produce(self, num=1): | |
self.count += num | |
def consume(self): | |
if self.count: | |
self.count -= 1 | |
def isEmpty(self): | |
return not self.count | |
class Producer(Thread): | |
def __init__(self, condition, itemq, sleeptime=1): | |
super(Producer, self).__init__() | |
self.cond = condition | |
self.itemq = itemq | |
self.sleeptime = sleeptime | |
def run(self): | |
cond = self.cond | |
itemq = self.itemq | |
while 1: | |
cond.acquire() | |
print currentThread() | |
itemq.produce() | |
cond.notifyAll() | |
cond.release() | |
time.sleep(self.sleeptime) #switch from currentThread to another thread | |
class Consumer(Thread): | |
def __init__(self, condition, itemq, sleeptime=2): | |
super(Consumer, self).__init__() | |
self.cond = condition | |
self.itemq = itemq | |
self.sleeptime = sleeptime | |
def run(self): | |
cond = self.cond | |
itemq = self.itemq | |
while 1: | |
time.sleep(self.sleeptime) #because has two consume thread, sleep to switch another thread | |
cond.acquire() | |
while itemq.isEmpty(): | |
print 'cond wait ' | |
cond.wait() | |
print 'cond wait cancel' | |
itemq.consume() | |
print currentThread() | |
cond.release() | |
if __name__=="__main__": | |
q = ItemQ() | |
cond = Condition() | |
pro = Producer(cond, q) | |
cons1 = Consumer(cond, q) | |
cons2 = Consumer(cond, q) | |
pro.start() | |
cons1.start() | |
cons2.start() | |
while 1: | |
pass |
Author
zhyq0826
commented
Sep 8, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment