CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

An example using a mutex

Continuing our banking example, we can see how a mutex may be use to protect a shared resource (here, balance) by requiring threads to lock (own) the mutex before updating the resource:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int balance = 0;

pthread_mutex_t mutexbalance = PTHREAD_MUTEX_INITIALIZER;

void deposit(int amount)
{
    pthread_mutex_lock(&mutexbalance);
    {
        int currbalance = balance;      // read shared balance
        currbalance    += amount;
        balance         = currbalance;  // write shared balance
    }
    pthread_mutex_unlock(&mutexbalance);
}

void withdraw(int amount)
{
    pthread_mutex_lock(&mutexbalance);
    {
        int currbalance = balance;       // read shared balance
        if(currbalance >= amount) {
            currbalance -= amount;
            balance      = currbalance;  // write shared balance
        }
    }
    pthread_mutex_unlock(&mutexbalance);
}

    create threads...
....
    deposit(200);      // thread 1
    withdraw(100);     // thread 2
    deposit(500);      // thread 1
    withdraw(200);     // thread 3

 


CITS2002 Systems Programming, Lecture 21, p3, 10th October 2023.