Created
May 6, 2019 21:32
-
-
Save starzia/b6456d74be2f3ab12a0dd4cbff252717 to your computer and use it in GitHub Desktop.
A simple concurrency bug demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <pthread.h> | |
static volatile int counter = 0; | |
static const int LOOPS = 1e7; | |
void* mythread(void* arg) { | |
printf("%s: begin\n", (char*)arg); | |
int i; | |
for (i=0; i<LOOPS; i++) { | |
counter++; | |
} | |
printf("%s: done\n", (char*)arg); | |
return NULL; | |
} | |
int main(int argc, char* argv[]) { | |
pthread_t p1, p2; | |
printf("main: begin (counter = %d)\n", counter); | |
pthread_create(&p1, NULL, mythread, "A"); | |
pthread_create(&p2, NULL, mythread, "B"); | |
// wait for threads to finish | |
pthread_join(p1, NULL); | |
pthread_join(p2, NULL); | |
printf("main: done with both (counter = %d, goal was %d)\n", | |
counter, 2*LOOPS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment