The basic unit of execution in the Concurrence framework is the Tasklet.
The basic unit of communication between tasks is the Message.
A message is defined like this:
class MSG_XXX(Message): pass
Note
By convention, Messages should have UPPERCASE names that start with MSG_ .
Every Tasklet has a mailbox where it receives messages from other tasks.
A Tasklet receives and processes pending messages using the following pattern:
for msg, args, kwargs in Tasklet.receive():
if msg.match(MSG_XXX):
...
elif msg.match(MSG_YYY):
...
else:
...
The Tasklet will call the receive() iterator in order to receive any pending messages. If there are no pending messages, the Tasklet will block until a message arrives. Each message is accompanied by a tuple args of positional arguments and a dictionary kwargs of named arguments, both of which may be empty. The Tasklet will then determine what to do by matching the msg using the match() method.
An example of using messages to communicate between tasks:
from concurrence import Tasklet, Message, dispatch
class MSG_GREETING(Message): pass
class MSG_FAREWELL(Message): pass
def printer():
for msg, args, kwargs in Tasklet.receive():
if msg.match(MSG_GREETING):
print 'Hello', args[0]
elif msg.match(MSG_FAREWELL):
print 'Goodbye', args[0]
else:
pass #unknown msg
def main():
printer_task = Tasklet.new(printer)()
MSG_GREETING.send(printer_task)('World')
MSG_FAREWELL.send(printer_task)('World')
if __name__ == '__main__':
dispatch(main)
In this example the main task starts a new task printer that forever listens for messages using the receive() iterator.
The main task then sends 2 messages to the printer task, which will respond by printing the appropriate message to the console.
Note
Messages by default are ‘asynchronous’ e.g., the sender does not wait for the receiver task to finish processing it. There is also support for ‘synchronous’ messages by using the call() method of the Message class. In that case, the receiver will have to reply() to the incoming message and the caller will block until the reply has been received.