diff options
author | toni <matzeton@googlemail.com> | 2015-12-08 18:38:31 +0100 |
---|---|---|
committer | toni <matzeton@googlemail.com> | 2015-12-08 18:38:31 +0100 |
commit | 9e6551c1b97638a5a29821837c5e1d07de8f1f4b (patch) | |
tree | defdaf7fc9f8bf8886ee4f95d60d3de5c523d9e4 /parallel/nosync.c | |
parent | 0d01b813509553260eae35b645f040d2b97fe3eb (diff) | |
parent | 7197dcc620d71f052d4114d7419132b8c0204178 (diff) |
Merge branch 'master' of github.com:lnslbrty/foo-scripts
Diffstat (limited to 'parallel/nosync.c')
-rw-r--r-- | parallel/nosync.c | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/parallel/nosync.c b/parallel/nosync.c new file mode 100644 index 0000000..9ddc5a3 --- /dev/null +++ b/parallel/nosync.c @@ -0,0 +1,68 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <pthread.h> + +#include <assert.h> + + +struct thread_data { + pthread_t thrd; + int id; + int result; +}; + + +#define NTHREADS 8 +static const unsigned int nthreads = NTHREADS; +static const unsigned int iterations = 4000; +static struct thread_data thrds[NTHREADS]; + +/* r/w by threads */ +static int sum = 0; + + +void * +thread_func(void *arg) +{ + int i; + int s; + struct thread_data *td = (struct thread_data *) arg; + + printf("Thread %d started ..\n", td->id); + + /* critical section - no sync */ + s = sum; // READ + for (i = 0; i < iterations; i++) { + s++; + } + sum = s; // WRITE + + return NULL; +} + +int +main(int argc, char *argv[]) +{ + int i; + + for (i = 0; i < nthreads; i++) { + thrds[i].id = i; + thrds[i].result = 0; + assert( pthread_create( &(thrds[i].thrd), NULL, thread_func, (void*)&thrds[i] ) == 0 ); + } + + for (i = 0; i < nthreads; i++) { + assert( pthread_join(thrds[i].thrd, NULL) == 0 ); + } + + printf("Expected result: sum == %d\n", iterations*nthreads); + if (sum == iterations*nthreads) { + printf("It worked randomly, lucky dude ..\n"); + } else { + printf("This should be the common occasion: sum == %d\n", sum); + } + + return 0; +} |