Reputation: 1692
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