Question: 8. The code below is a thread program with synchronization via mutex. Answer the following questions: 1. how many threads are created? Highlight and mark

8. The code below is a thread program with synchronization via mutex. Answer the following questions:

1. how many threads are created? Highlight and mark on the code.

2. When thread start to execute, which function does it start to run?

3. Describe the execution logic of this program and the expected output.

4. Modify the program so the execution order of the children threads will be reversed.

int value[]={1,2,3,4,5,6,7,8,9,10};

int counter = 10;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main(int argc, char *argv[])

{

pthread_t tid[10];

pthread_attr_t attr[10];

for(int j=0; j<10; j++)

{

pthread_attr_init(&attr[j]);

pthread_create(&tid[j],&attr[j],runner,&value[j]);

}

for(int k=0; k<10; k++)

{

pthread_join(tid[k],NULL);

}

}

void *runner(void *param)

{

while(i>0)

{

if(*(int *)param == counter)

{

printf("param = %d ", *(int *)param);

pthread_mutex_lock(&mutex);

counter --;

pthread_mutex_unlock(&mutex);

sleep(random());

pthread_yield();

}

else {

pthread_yield();

}

}

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!