4.3.1. Shared BufferΒΆ

See Shared Buffer Problem.

We only need to enforce mutual exclusion with a single lock or semaphore to correctly solve this problem. In Python, a Lock object from the threading module is a semaphore where s == 1. That is, only one thread is allowed to hold the lock at a time (mutual exclusion).

import threading

class shared_acct(Object):
    def __init__(self, balance):
        self.lock = threading.Lock()
        self.balance = balance

    def deposit(self, amount):
        self.lock.acquire()
        self.balance += amount
        self.lock.release()
        return True

    def withdraw(self, amount):
        self.lock.acquire()
        if( amount > self.balance ):
            self.lock.release()
            return False
        else:
            self.balance -= amount
            self.lock.release()
            return True

    def get_balance(self):
        self.lock.acquire()
        bal = self.balance
        self.lock.release()
        return bal