![subject](/tpl/images/cats/informatica.png)
Computers and Technology, 27.10.2020 23:00 help445492
In the example program below, a variable is used to protect the critical section. Why did it fail? Use pthread_mutex_init( ) and pthread_mutex_lock( )/pthread_mutex_unlock( ) system call to modify this program so that the result is correct.
// when input thread number to be 100
// then two output are different
#include
#include
char USAGE[] = "naive_lock n_threads\n"
"USAGE: run n threads with a naive lock\n";
int lock = 0; //0 for unlocked, 1 for locked
int shared = 0; //shared variable
void * incrementer(void * args){
int i;
for(i=0;i 0); //spin until unlocked
lock = 1; //set lock
shared++; //increment
lock = 0; //unlock
}
return NULL;
}
int main(int argc, char * argv[]){
pthread_t * threads;
int n, i;
if(argc < 2){
fprintf(stderr, "USAGE: program number_of_thread\n");
exit(1);
}
//convert argv[1] to a long
if((n = atol(argv[1])) == 0){
fprintf(stderr, "ERROR: Invalid number of threads\n");
exit(1);
}
//allocate array of pthread_t identifiers
threads = calloc(n, sizeof(pthread_t));
//create n threads
for(i=0;i
pthread_create(&threads[i], NULL, incrementer, NULL);
}
//join all threads
for(i=0;i
pthread_join(threads[i], NULL);
}
//print shared value and result
printf("Shared: %d\n",shared);
printf("Expect: %d\n",n*100);
return 0;
}
![ansver](/tpl/images/cats/User.png)
Answers: 1
![](/tpl/images/ask_question.png)
![](/tpl/images/ask_question_mob.png)
Other questions on the subject: Computers and Technology
![image](/tpl/images/cats/informatica.png)
Computers and Technology, 22.06.2019 09:00, sophiawatson70
Create a cell reference in a formula by typing in the cell name or a. right-clicking the cell. b. clicking the cell. c. clicking the column where the cell is located. d. clicking the row where the cell is located.
Answers: 1
![image](/tpl/images/cats/informatica.png)
Computers and Technology, 23.06.2019 07:00, Dvrsug8598
You need a quick answer from a coworker. the most effective way to reach your coworker is through a. cloud server b. instant message c. teleconference d. telepresence
Answers: 1
![image](/tpl/images/cats/informatica.png)
You know the right answer?
In the example program below, a variable is used to protect the critical section. Why did it fail? U...
Questions in other subjects:
![Konu](/tpl/images/cats/mat.png)
Mathematics, 02.02.2020 21:58
![Konu](/tpl/images/cats/mat.png)
Mathematics, 02.02.2020 21:58
![Konu](/tpl/images/cats/mat.png)
![Konu](/tpl/images/cats/biologiya.png)
![Konu](/tpl/images/cats/mat.png)
Mathematics, 02.02.2020 21:58
![Konu](/tpl/images/cats/mat.png)
Mathematics, 02.02.2020 21:58
![Konu](/tpl/images/cats/mat.png)
Mathematics, 02.02.2020 21:59
![Konu](/tpl/images/cats/es.png)
![Konu](/tpl/images/cats/biologiya.png)