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

Other questions on the subject: Computers and Technology

image
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
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
Computers and Technology, 24.06.2019 03:00, paguy12
What is one potential problem associated with an organization purchasing new technology early in its lifecycle
Answers: 1
image
Computers and Technology, 24.06.2019 17:40, lia1690
Which of the following processes applications across multiple computing devices? a. functional application b. distributed system c. workgroup information silo d. information silo
Answers: 3
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
Mathematics, 02.02.2020 21:58
Konu
Mathematics, 02.02.2020 21:59