Skip to content

Instantly share code, notes, and snippets.

@gallir
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gallir/d6c22cf4e0c510f359ff to your computer and use it in GitHub Desktop.
Save gallir/d6c22cf4e0c510f359ff to your computer and use it in GitHub Desktop.
It shows OoO execution and/or write buffers and/or cache weak consistency
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#define NUM_THREADS 4
#define MAX_COUNT 10000000
struct tdata {
int tid;
int *counter;
};
int turns[NUM_THREADS];
void *count(void *ptr) {
long i, max = MAX_COUNT/NUM_THREADS;
int tid = ((struct tdata *) ptr)->tid;
int *counter = ((struct tdata *) ptr)->counter;
int number = 0, next = (tid+1)%NUM_THREADS;
for (i=0; i < max; i++) {
while(turns[tid] != number);
number++;
*counter+= 1; // The global variable, i.e. the critical section
turns[next]++;
}
printf("End %d counter: %d\n", tid, *counter);
pthread_exit(NULL);
}
int main (int argc, char *argv[]) {
pthread_t threads[NUM_THREADS];
int rc, i;
struct tdata id[NUM_THREADS];
int counter = 0;
turns[0] = 0;
for(i=1; i<NUM_THREADS; i++){
turns[i] = -1;
}
for(i=0; i<NUM_THREADS; i++){
id[i].counter = &counter;
id[i].tid = i;
rc = pthread_create(&threads[i], NULL, count, (void *) &id[i]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
for(i=0; i<NUM_THREADS; i++){
pthread_join(threads[i], NULL);
}
printf("Counter value: %d Expected: %d\n", counter, MAX_COUNT);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment