Last active
August 29, 2015 14:16
-
-
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
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 <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