Question: A solution to avoid race conditions is to use a tool offered by most operating systems: semaphores . A semaphore is a special integer variable
A solution to avoid race conditions is to use a tool offered by most operating systems: semaphores. A semaphore is a special integer variable that is used for controlling access to shared resources. The PThreadlibrary defines a Semaphore object in semaphore.h. There are 3 types of operations defined on a semaphore:
Initialization: In C, this is done by calling the sem_init function. For example the following initializes a shared semaphore (called mutex) to 1.
sem_t mutex = sem_init(&mutex, 0, 1);
Decrement and Wait: The value of the semaphore is decremented and if its value becomes negative, then the thread is blocked. This can be done by calling:
sem_wait(&mutex);
Increment and Signal: The value of the semaphore is incremented and if its value becomes negative or equal to zero, then a thread that was blocked is unblocked.In Java, this can be done by calling:
sem_post(&mutex);
Binary semaphores are simply semaphores that can take on the values 0 and 1.
Modify the file rc.c:
| #include #include #include #include int global = 0; sem_t mutex; void *inc( void *ptr ) { int i; for(i = 0; i < 9000000; i++){ sem_wait(&mutex); global++; sem_post(&mutex); } } void *dec( void *ptr ) { int i; for(i = 0; i < 9000000; i++){ sem_wait(&mutex); global--; sem_post(&mutex); } } int main() { pthread_t thread1, thread2; sem_init(&mutex, 0, 1); pthread_create( &thread1, NULL, inc, NULL); pthread_create( &thread2, NULL, dec, NULL); pthread_join( thread1, NULL); pthread_join( thread2, NULL); sem_destroy(&mutex); printf("Final global = %d ", global); exit(0); } |
Compile the program again:
student@Ubuntu:~/labs/lab3$ gcc -pthread rc.c -o rc
Run the program several times again:
student@Ubuntu:~ /labs/lab3 $ ./rc
What are the possible outputs this time? Explain in detail how the use of semaphores guarantees that the critical sections:
global++
global--
wont be accessed concurrently by the two threads.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
