Diagnosing a mutex that does not protect

Four threads each call the function below, and main calls pthread_join on all four before printing total. The intended result is 400000, but a test run prints a smaller number. Assume all pthread calls succeed.


C
long total = 0;   /* global */

void *worker(void *arg) {
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, NULL);
    for (int i = 0; i < 100000; i++) {
        pthread_mutex_lock(&lock);
        total++;
        pthread_mutex_unlock(&lock);
    }
    pthread_mutex_destroy(&lock);
    return NULL;
}


Which statement correctly identifies the synchronization error behind the incorrect result?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Parallel Programming Questions: