Question: #include #include common _ threads.h int done = 0 ; void * worker ( void * arg ) { printf ( this should

#include
#include "common_threads.h"
int done =0;
void* worker(void* arg){
printf("this should print first
");
done =1;
return NULL;
}
int main(int argc, char *argv[]){
pthread_t p;
Pthread_create(&p, NULL, worker, NULL);
while (done ==0)
;
printf("this should print last
");
return 0;
}
What synchronized primitives can be added to above program to make the mutual exclusion effectively and effeciently ? Choose all options suitable.
Add join() in the main() thread to force it to wait for the completion of the worker thread.
Add a lock surrounding the global variable 'done' in both main() and worker thread for controlled access.
Add condition varaiable to coordinate the action between main() thread and worker thread. Specifically, add wait() inside the while loop in the main() to suspend the its execution until the worker thread completes the change on the global variable and notifies the main() by invoking signal().
Change the while (done ==0) to if (done ==0) to stop the spin waiting of main thread. This avoid wasting the CPU cycle.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!