Question: Modify the file rc.c: #include #include #include //compile and link with -pthread #include int global = 0; sem_t mutex; void *inc( void *ptr ) {
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
