Mutual Exclusion

Step 1: Mutual Exclusion

A lock's one job: only one client may hold a named resource at a time. Everyone else has to wait. Start with the core of it, an owner map.

  • acquire(name, client_id): grab the lock. Return True if it was free (now held by client_id), False if someone else already holds it.
  • release(name, client_id): let go. Only the current owner may release it: return True if released, False otherwise.
Hints
Starter code
class LockManager:
    def __init__(self):
        self._owner = {}   # name -> client_id

    def acquire(self, name, client_id):
        """Return True if the lock was free and is now held by client_id."""
        # TODO: look up name in the self._owner map. When no one holds it,
        #   record client_id as the new owner and answer True.
        #   When another client already holds it, change nothing and answer False.
        pass

    def release(self, name, client_id):
        """Only the owner may release. Return True if released."""
        # TODO: compare the owner stored for name in self._owner with client_id.
        #   Only on a match, drop that entry and answer True.
        #   No holder, or a different holder, answers False and changes nothing.
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.