Skip to content

Instantly share code, notes, and snippets.

Created September 15, 2016 23:13
Show Gist options
  • Save anonymous/2db63637fd3b81242ecc6fa777a87b65 to your computer and use it in GitHub Desktop.
Save anonymous/2db63637fd3b81242ecc6fa777a87b65 to your computer and use it in GitHub Desktop.
C code
#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