Appendix B. Supplementary Material

This appendix contains some additional code related to the case studies presented in the book. You might find this material helpful to round out your understanding of the examples.

Cutlery Example Using Asyncio

“Case Study: Robots and Cutlery” analyzed a race condition bug caused by multiple threads modifying the cutlery records in the global “kitchen” object instance. For completeness, here is how we might create an async version of the solution.

There is a specific point I want to highlight about the observability of concurrency in the asyncio approach, shown in Example B-1.

Example B-1. Cutlery management using asyncio
import asyncio

class CoroBot():  1
  def __init__(self):
    self.cutlery = Cutlery(knives=0, forks=0)
    self.tasks = asyncio.Queue()  2

  async def manage_table(self):
    while True:
      task = await self.tasks.get()  3
      if task == 'prepare table':
        kitchen.give(to=self.cutlery, knives=4, forks=4)
      elif task == 'clear table':
        self.cutlery.give(to=kitchen, knives=4, forks=4)
      elif task == 'shutdown':
        return

from attr import attrs, attrib

@attrs
class Cutlery:
    knives = attrib(default=0)
    forks = attrib(default=0)

    def give(self, to: 'Cutlery ...

Get Using Asyncio in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.