Skip to content

Instantly share code, notes, and snippets.

@starzia
Created May 6, 2019 21:32
Show Gist options
  • Save starzia/b6456d74be2f3ab12a0dd4cbff252717 to your computer and use it in GitHub Desktop.
Save starzia/b6456d74be2f3ab12a0dd4cbff252717 to your computer and use it in GitHub Desktop.
A simple concurrency bug demo
#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