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;
}
Answers: 1
Computers and Technology, 21.06.2019 14:30, leannamat2106
Asoftware program that includes tools for entering, editing, and formatting text and graphics is called a word processing program. true or false?
Answers: 1
Computers and Technology, 21.06.2019 22:40, hePandaKing3689
State the parts of a variable declaration?
Answers: 2
Computers and Technology, 22.06.2019 10:30, ghazanfarwaheed7967
Auniversity wants to install a client-server network. which feature do you think is important for them as they set up the network? sending email blocking multiple people to use the same file low security low set up cost limited access to files
Answers: 1
Computers and Technology, 22.06.2019 19:10, sammigrace5820
How might the success of your campaign be affected if you haven’t carefully completed all field data or if you accidentally insert the wrong merge field in the document?
Answers: 1
In the example program below, a variable is used to protect the critical section. Why did it fail? U...
English, 12.03.2021 21:00
Mathematics, 12.03.2021 21:00
Mathematics, 12.03.2021 21:00
Physics, 12.03.2021 21:00
Mathematics, 12.03.2021 21:00
Biology, 12.03.2021 21:00
Biology, 12.03.2021 21:00