Created
August 2, 2016 13:16
-
-
Save plucury/719c9d0adc803f95a5ce6955ba1f2804 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# coding=utf-8 | |
import threading | |
class BlockingQ(object): | |
def __init__(self, size): | |
self.size = size | |
self.q = [] | |
self.lock = threading.Condition() | |
def push(self, obj): | |
self.lock.acquire() | |
while len(self.q) >= self.size: | |
print 'wait push %s\n' % obj | |
self.lock.wait() | |
self.q.insert(0, obj) | |
self.lock.notify() | |
self.lock.release() | |
def pop(self): | |
self.lock.acquire() | |
while not self.q: | |
print 'wait pop\n' | |
self.lock.wait() | |
r = self.q.pop() | |
# '''an awakened thread does not actually return from its wait() call | |
# until it can reacquire the lock.''' | |
# 所以这里notify以后push并没有得到锁,而要等到release之后才能得到锁开始运行 | |
self.lock.notify() | |
self.lock.release() | |
return r | |
q = BlockingQ(3) | |
def do_push(): | |
for i in range(10): | |
q.push(i) | |
def do_pop(): | |
while True: | |
o = q.pop() | |
print '%s\n' % o | |
push = threading.Thread(target=do_push) | |
pop = threading.Thread(target=do_pop) | |
push.start() | |
pop.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment