Shared Resource


Introduction

This example shows how two threads ensure atomic access to a shared resource using a mutex. The example contains three files:
  • main.cpp - constructs the mutex and the two threads that share a resource (a simple integer)
  • t1.cpp - contains t1, the one thread function
  • t2.cpp - contains t2, the other thread function

Source code

//==============================
//main.cpp
//==============================
 
#include<taskLib.h>
#include<semLib.h>
#include<iostream>
 
using namespace std;
 
// Prototypes for thread functions
void t1(SEM_ID id, int* shrd);
void t2(SEM_ID id, int* shrd);
 
// the shared resource
int shared=0;
 
void myMain()
{
 
 // construct the mutex
 SEM_ID mid = semMCreate(SEM_Q_PRIORITY | SEM_DELETE_SAFE | SEM_INVERSION_SAFE | SEM_FULL );
 
 // Spawn (= create & activate) the two tasks
 taskSpawn("Thread 1", 100, 0, 0x1000, (FUNCPTR)t1, (int)mid, (int)&shared, 0, 0, 0, 0, 0, 0, 0, 0);
 taskSpawn("Thread 2", 100, 0, 0x1000, (FUNCPTR)t2, (int)mid, (int)&shared, 0, 0, 0, 0, 0, 0, 0, 0);
 
 // Wait a while before exit
 taskDelay(300);
}
 

 //==============================
 // t1.cpp
 // ==============================
 
 #include<taskLib.h>
 #include<semLib.h>
 #include<iostream>
 
 using namespace std;
 
 
 void t1(SEM_ID id, int* shared)
 {
 cout << "t1 attempts to take the mutex" << endl;
 semTake(id, WAIT_FOREVER);
 cout << "t1 has the mutex and can now change the resource." << endl;
 (*shared)++;
 taskDelay(100); // wait a while before giving the mutex
 cout << "t1 changed the resource - it is now " << *shared << endl;
 cout << "t1 will now give the mutex" << endl;
 semGive(id);
 cout << "t1 gave the mutex" << endl;
 }

 //==============================
// t2.cpp
// ==============================
 
#include<taskLib.h>
#include<semLib.h>
#include<iostream>
 
using namespace std;
 
 
void t2(SEM_ID id, int* shared)
{
 cout << " t2 attempts to take the mutex" << endl;
 semTake(id, WAIT_FOREVER);
 cout << " t2 has the mutex and can now change the resource." << endl;
 (*shared)++;
 taskDelay(100); // wait a while before giving the mutex
 cout << " t2 changed the resource - it is now " << *shared << endl;
 cout << " t2 will now give the mutex" << endl;
 semGive(id);
 cout << " t2 gave the mutex" << endl;
}

Output results

This is a screen dump of the execution of the above source code:
-> myMain
t1 attempts to take the mutex
t1 has the mutex and can now change the resource.
 t2 attempts to take the mutex
t1 changed the resource - it is now 1
t1 will now give the mutex
t1 gave the mutex
 t2 has the mutex and can now change the resource.
 t2 changed the resource - it is now 2
 t2 will now give the mutex
 t2 gave the mutex
value = 0 = 0x0
->