Question: What is the problem with this program? Now, create a new version of the program, and using mutex locks (lock inside the for loop), fix

What is the problem with this program? Now, create a new version of the program, and using mutex locks (lock inside the for loop), fix the code.

Then, in another new version of the program, move the locks so that they lock and unlock only once per thread (outside the for loop). Verify the correct value is still obtained.

#include #include #include #include

// A normal C function that is executed as a thread // when its name is specified in pthread_create() void *myThreadFunc(void *vargp) { sleep(1); // to give one second break for each thread else all the threads will execute randomly int i; static int var = 1; /*Shared varible for all the thread*/ static int th = 1; /* Index to track threads */ for(i = 0; i < 1000; ++i) /* Loop to increament and print shared varible by each thread*/ printf("Printing from Thread %d with shared variable value %d ",th, var++); th++; return NULL; }

int main() { int i = 0; pthread_t thread_id[100]; /*Array to hold thread_id which are used to handle each thread*/ printf("Before Thread ");

for(i = 0; i < 100; ++i) /* Loop to start new threads */ pthread_create(&thread_id[i], NULL, myThreadFunc, NULL); /* pthread_create is a standard function to create new thread*/

for(i = 0; i < 100; ++i) pthread_join(thread_id[i], NULL); /* This is used to wait for the thread to execute completely*/

printf("After all Threads "); exit(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!