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 #include #include #include #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

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 Databases Questions!