Created
June 8, 2013 01:52
-
-
Save mumrah/5733579 to your computer and use it in GitHub Desktop.
Serializing operations in Python, with blocking behavior on the caller side
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
from threading import Thread, Event | |
from Queue import Queue | |
class Proc(Thread): | |
def __init__(self, in_queue): | |
Thread.__init__(self) | |
self.in_queue = in_queue | |
self.die = Event() | |
def stop(self): | |
self.die.set() | |
def run(self): | |
while True: | |
if self.die.is_set(): | |
break | |
(msg, e) = self.in_queue.get() | |
e.set() | |
queue = Queue() | |
proc = Proc(queue) | |
proc.daemon = True | |
proc.start() | |
def send(msg): | |
e = Event() | |
queue.put((msg, e)) | |
e.wait() | |
print "sent %s" % msg | |
class SenderA(Thread): | |
def run(self): | |
send("a") | |
send("b") | |
send("c") | |
class SenderB(Thread): | |
def run(self): | |
send("x") | |
send("y") | |
send("z") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment