Easy Concurrency with Stackless Python
First, you initialize five flowers, and then five bees. As each bee or flower is initialized, it are added to the stackless scheduler through their call to stackless.tasklet in their __init__ method. So, at the end of the initialization, the stackless scheduler looks like this:
flower 0 flower 1 flower 2 flower 3 flower 4 bee 0 bee 1 bee 2 bee 3 bee 4
Then, you start running through the queue with the call to stackless.run(). First, the five flowers start listening on their channels. When the queue runs to bee 0, bee 0 picks a random flower from its list of pointers to the flower objects, and sends itself as a message. The receiving flower updates the bee's nectar count, and then goes back to listening. The bee, after having passed its message, puts itself back on the end of the queue, by calling another random flower channel. It continues to do this until it's filled up on nectar.
Each channel has its own queue that track messages from senders. As the channel manager (in this case, the flower) works through its queue, it doesn't prevent new messages from coming in. In that way, no messages are lost, and no single message blocks the entire flow of the program.
Although this is obviously a trivial example, it covers all the essentials of what Stackless provides. With three simple tools, tasklets, channels, and a scheduler, you can build a wide array of concurrent programs.
About the Author