Created
September 15, 2016 23:13
-
-
Save anonymous/2db63637fd3b81242ecc6fa777a87b65 to your computer and use it in GitHub Desktop.
C code
This file contains 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> | |
#define NTHREADS 5 | |
void *myFun(void *x) | |
{ | |
int tid; | |
tid = *((int *) x); | |
printf("Hi from thread %d!\n", tid); | |
return NULL; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
pthread_t threads[NTHREADS]; | |
int thread_args[NTHREADS]; | |
int rc, i; | |
/* spawn the threads */ | |
for (i=0; i<NTHREADS; ++i) | |
{ | |
thread_args[i] = i; | |
printf("spawning thread %d\n", i); | |
rc = pthread_create(&threads[i], NULL, myFun, (void *) &thread_args[i]); | |
} | |
/* wait for threads to finish */ | |
for (i=0; i<NTHREADS; ++i) { | |
rc = pthread_join(threads[i], NULL); | |
} | |
return 1; | |
} | |
// spawning thread 0 | |
// spawning thread 1 | |
// Hi from thread 0! | |
// spawning thread 2 | |
// Hi from thread 1! | |
// spawning thread 3 | |
// spawning thread 4 | |
// Hi from thread 4! | |
// Hi from thread 3! | |
// Hi from thread 2! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment