Skip to content

Instantly share code, notes, and snippets.

@regehr
Created March 28, 2017 21:42
Show Gist options
  • Save regehr/1bf297347da627beaf82a5930d5b33d6 to your computer and use it in GitHub Desktop.
Save regehr/1bf297347da627beaf82a5930d5b33d6 to your computer and use it in GitHub Desktop.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
volatile int x, y, tmp1, tmp2;
void *t0(void *arg) {
x = 1;
tmp1 = y;
return 0;
}
void *t1(void *arg) {
y = 1;
tmp2 = x;
return 0;
}
void pthread_create_or_die(pthread_t *thread, void *(*start_routine)(void *)) {
int res = pthread_create(thread, 0, start_routine, 0);
if (res != 0) {
perror("pthread_create");
exit(-1);
}
}
void pthread_join_or_die(pthread_t thread) {
int res = pthread_join(thread, 0);
if (res != 0) {
perror("pthread_join");
exit(-1);
}
}
int main(void) {
int a = 0, b = 0, c = 0, d = 0;
for (long i = 0; i < 10000000; i++) {
x = y = tmp1 = tmp2 = 0;
pthread_t thread0, thread1;
pthread_create_or_die(&thread0, t0);
pthread_create_or_die(&thread1, t1);
pthread_join_or_die(thread0);
pthread_join_or_die(thread1);
if (tmp1 == 0 && tmp2 == 1)
a++;
if (tmp1 == 1 && tmp2 == 0)
b++;
if (tmp1 == 0 && tmp2 == 0)
c++;
if (tmp1 == 1 && tmp2 == 1)
d++;
}
printf("0,1: %d 1,0: %d 0,0: %d 1,1: %d\n", a, b, c, d);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment