subject

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
Answers: 1

Another question on Computers and Technology

question
Computers and Technology, 22.06.2019 03:40
Mary's manager told her she should insert a graphic into her documentwrite mary a brief note describing how to insert a graphicin a word processing document.
Answers: 1
question
Computers and Technology, 22.06.2019 10:00
Jackson is teaching the decimal number system. he wants his students to know how to expand numbers by powers of 10. which is the correct order in which digits are assigned values in the decimal number system?
Answers: 1
question
Computers and Technology, 23.06.2019 14:30
Open this link after reading about ana's situation. complete each sentence using the drop-downs. ana would need a minimum of ato work as a translator. according to job outlook information, the number of jobs for translators willin the future.
Answers: 3
question
Computers and Technology, 24.06.2019 02:00
Write an expression that will cause the following code to print "equal" if the value of sensorreading is "close enough" to targetvalue. otherwise, print "not equal". ex: if targetvalue is 0.3333 and sensorreading is (1.0/3.0), output is:
Answers: 1
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
question
Mathematics, 22.01.2021 14:00
question
Mathematics, 22.01.2021 14:00