Question: Consider the following partially implemented code: #define NUM_THREADS 10 semaphore S = 2; int data[5], index = 0; void runner(void* param) { wait(&S); //LINE 1

Consider the following partially implemented code:

#define NUM_THREADS 10

semaphore S = 2; int data[5], index = 0;

void runner(void* param) { wait(&S); //LINE 1

data[index] += 5; printf("%d ", data[index]); index = ++index % 5;

signal(&S); //LINE 2 pthread_exit(0); }

int main() { pthread_t threads[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { pthread_create(threads[i], NULL, runner, NULL); } for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } return 0; }

The provided code uses a semaphore in attempt to guard the critical section between LINE 1 and LINE 2, as indicated in comments. In the current form, the critical section is not properly guarded by the semaphore. Without using an additional mutex lock or semaphore, show how you could change the code to properly guard the critical section. Indicate which lines of code you would change to fix the issue and describe what impact the fix may have on multi-threading the program. Justify your change(s) with reasoning as to why they would work.

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!