Skip to content

Instantly share code, notes, and snippets.

@objarni
Last active August 29, 2015 14:06
Show Gist options
  • Save objarni/ccd6b13517d5900abced to your computer and use it in GitHub Desktop.
Save objarni/ccd6b13517d5900abced to your computer and use it in GitHub Desktop.
A code sketch of a nice simple asynchronous messaging library I'd like to call "Buz" - standing for lots of chatter - buzz, and it's a MessageBus architecturally. And it's a TLA that's nice to say ;)
from buz import Buz, Inbox
buz = Buz()
# Sending a message asynchronously is ridiculously simple
def long_computation(self):
# looong slow algorithm (possibly involving polling I/O ports!)
buz.publish(SomeMessage(..))
# Remember the hell we go through to do things in parallell
# with UI threads? They don't exist with a publish-subscribe
# architecture...
class SomeUIClass(object):
# Subscribing to several message types is intuitive,
# just create an "Inbox" and subscribe to some message types.
def __init__(self, buz):
self.inbox = Inbox()
buz.add_subscriber(inbox, SomeMessage, self.some_handler)
buz.add_subscriber(inbox, SomeOtherMsg, self.some_other_handler)
# Handling incoming messages is sweet and we're in full control
# That is since we are running inside the UI thread no worry about
# widget state messup.
# We do have to call this method repeatedly though, but that's
# a no-brainer in most GUI toolkits (timeout/repeat events on UI thread).
def check_inbox(self):
self.inbox.handle_messages()
# In some button click handler we fire off a message to be handled
# by a "computation thread", knowing we will receive an answer
# on our own thread in the future, when the other actor/thread
# publishes the result.
def handle_go_click(self):
buz.publish(DoHeavyStuff(10011))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment