PTN
PTN

Reputation: 1692

Multiple threads increment shared variable without locks but return "unexpected" output

I'm invoking 100 threads, and each threads should increment a shared variable 1000 times. Since I'm doing this without using mutex locks, the expected output should NOT be 100000. However, I'm still getting 100000 every time.

This is what I have

volatile unsigned int count = 0;  
void *increment(void *vargp);

int main() {
    fprintf(stdout, "Before: count = %d\n", count);

    int j;
    // run 10 times to test output
    for (j = 0; j < 10; j++) {
        // reset count every time
        count = 0;

        int i;
        // create 100 theads
        for (i = 0; i < 100; i++) {
            pthread_t thread;

            Pthread_create(&thread, NULL, increment, NULL);
            Pthread_join(thread, NULL);
        }

        fprintf(stdout, "After: count = %d\n", count);
    }

    return 0;
}          

void *increment(void *vargp) {
    int c;

    // increment count 1000 times
    for (c = 0; c < 1000; c++) {
        count++;
    }

    return NULL;
}  

Upvotes: 0

Views: 984

Answers (1)

Pinetwig
Pinetwig

Reputation: 705

The pthread_join() function suspends execution of the calling thread until the target thread terminates (source). After you create each thread, you wait for it to run and terminate. The threads never execute concurrently. Thus, there's no race condition

Upvotes: 2

Related Questions