Question: Complete the missing sections of code and explain the logic as well (if possible). CODE TO USE: semaphore_critical_reason.c // // semaphore_critical_reason.c // semaphore_critical_reason // #include
Complete the missing sections of code and explain the logic as well (if possible).
CODE TO USE: semaphore_critical_reason.c
// // semaphore_critical_reason.c // semaphore_critical_reason //
#include
void* protect_critical_region(void* n) { int i = 0, thread_num = (int)(long)n; bool finished = false; sem_t mutex, mutex2, mutex3;
while (!finished) { // TODO: FILL IN THIS LINE for (int j = 0; j < thread_num; ++j) { printf("\t\t\t"); } printf("CRITICAL(T%d) ", thread_num); // TODO: FILL IN THIS LINE
sleep(2);
// TODO: FILL IN THIS LINE for (int j = 0; j < thread_num; ++j) { printf("\t\t\t"); } printf("out of CRITICAL(T%d) ", thread_num); // TODO: FILL IN THIS LINE finished = i++ > 3;
// TODO: FILL IN THIS LINE for (int j = 0; j < thread_num; ++j) { printf("\t\t\t"); } printf("into non-critical(T%d) ", thread_num); // TODO: FILL IN THIS LINE } return NULL; }
#define N_THREADS 3
int main(int argc, const char* argv[]) { pthread_t tid[N_THREADS]; pthread_attr_t attr; pthread_attr_init(&attr); for (int i = 0; i < N_THREADS; ++i) { pthread_create(&tid[i], &attr, protect_critical_region, (void*)(long)i); } for (int i = 0; i < N_THREADS; ++i) { pthread_join(tid[i], NULL); } printf(" all %d threads joined", N_THREADS); printf(" End of program ");
return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
