diff options
author | EliteTK <tomasz.kramkowski@gmail.com> | 2015-06-19 19:12:12 +0100 |
---|---|---|
committer | EliteTK <tomasz.kramkowski@gmail.com> | 2015-06-19 19:12:12 +0100 |
commit | da87fcf25e0c94e57f00df84679cd6fadc56ed46 (patch) | |
tree | 3c53eea9db01039990455af870a2ca65e7e5a123 /pthreads.c | |
parent | 75d2e00662416224f4b745e0004f48f1fc1d9665 (diff) | |
parent | 7bf25fb8f0e4643a67894417a95d39e5901b1824 (diff) | |
download | c-stuff-da87fcf25e0c94e57f00df84679cd6fadc56ed46.tar.gz c-stuff-da87fcf25e0c94e57f00df84679cd6fadc56ed46.tar.xz c-stuff-da87fcf25e0c94e57f00df84679cd6fadc56ed46.zip |
Merge branch 'master' of https://github.com/EliteTK/c-stuff
Diffstat (limited to 'pthreads.c')
-rw-r--r-- | pthreads.c | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/pthreads.c b/pthreads.c new file mode 100644 index 0000000..87945fd --- /dev/null +++ b/pthreads.c @@ -0,0 +1,45 @@ +#define _GNU_SOURCE +#include <assert.h> +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <time.h> +#include <unistd.h> + +#define NUM_THREADS 100 + +typedef void *(* thread_func)(void *); + +void *somefunction(int *arg) +{ + int loops = rand(); + + for (int i = 0; i < loops; i++) { + pthread_yield(); + for (;i < loops; i++); + } + + printf("%d:\t%d\n", *arg, loops); + + return NULL; +} + +int main(void) +{ + srand(time(NULL)); + + pthread_t threads[NUM_THREADS]; + int args[NUM_THREADS]; + + for (int i = 0; i < NUM_THREADS; i++) { + args[i] = i; + if (pthread_create(&threads[i], NULL, (thread_func)somefunction, args + i)) + return EXIT_FAILURE; + } + + for (int i = 0; i < NUM_THREADS; i++) + if (pthread_join(threads[i], NULL)) + return EXIT_FAILURE; + + return EXIT_SUCCESS; +} |