Skip to content

Instantly share code, notes, and snippets.

@mumrah
Created June 8, 2013 01:52
Show Gist options
  • Save mumrah/5733579 to your computer and use it in GitHub Desktop.
Save mumrah/5733579 to your computer and use it in GitHub Desktop.
Serializing operations in Python, with blocking behavior on the caller side
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