Implementing the monitor object pattern
Another important topic in asynchronous programming is access to shared resources. When you work synchronously the access is sequential and traceable, but the gains in efficiency and scalability that asynchronous solutions provide mean that certain resources are more susceptible to race conditions that might lead to incorrect results. In these cases, access to shared resources can be controlled by putting a mutual exclusion mechanism in place that allows only one coroutine to perform operations over the resource, or even better a set of conditions to determine when a coroutine is allowed to access the resource.
In the following example (available at Chapter 6/monitor_queue.py) a bounded queue is used to represent shared resources that have a hard limit on capacity, two producers that act as clients have several tasks to be operated through the shared resources, and two customers act as operators that free up the resources:
import queue...