Created
December 27, 2014 21:23
-
-
Save Prince781/7f1baa2ff988f68bcd36 to your computer and use it in GitHub Desktop.
pthreads example
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 <stdio.h> | |
| #include <stdlib.h> | |
| #include <pthread.h> | |
| #include <sys/sysinfo.h> | |
| #define UBOUND 1000000000 | |
| void *tfunc(void *arg); | |
| int main(int argc, char *argv[]) | |
| { | |
| int i; | |
| int cpus = get_nprocs(); | |
| int nthreads; | |
| int (*vals)[2]; | |
| pthread_t *threads; | |
| nthreads = cpus; | |
| printf("num CPUs: %d\n", cpus); | |
| printf("num threads: %d\n", nthreads); | |
| threads = malloc((nthreads-1) * sizeof(pthread_t)); | |
| vals = malloc(nthreads * sizeof(int[2])); | |
| for (i=0; i<nthreads-1; ++i) { | |
| vals[i+1][0] = i+1; | |
| vals[i+1][1] = 0; | |
| pthread_create(threads+i, NULL, tfunc, vals+i+1); | |
| } | |
| vals[0][0] = 0; | |
| for (; vals[0][1] < UBOUND; ++vals[0][1]); | |
| printf("thread %d: val == %d\n", vals[0][0], vals[0][1]); | |
| for (i=0; i<cpus-1; ++i) | |
| if (pthread_join(threads[i], NULL)) { | |
| fprintf(stderr, "error joining thread #%d\n", i+1); | |
| return 2; | |
| } | |
| printf("done\n"); | |
| free(vals); | |
| free(threads); | |
| return 0; | |
| } | |
| void *tfunc(void *arg) | |
| { | |
| int (*arr)[2] = arg; | |
| int *val = *arr + 1; | |
| for (; *val < UBOUND; ++*val); | |
| printf("thread %d: val == %d\n", (*arr)[0], *val); | |
| return NULL; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment