Skip to content

Instantly share code, notes, and snippets.

@yohm
Created April 13, 2016 07:30
Show Gist options
  • Save yohm/14971a48a0250ffac350899552906a8f to your computer and use it in GitHub Desktop.
Save yohm/14971a48a0250ffac350899552906a8f to your computer and use it in GitHub Desktop.
testing coexistence of pthread and OpenMP
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <omp.h>
#define NTHREADS 4
void *myFun(void *x)
{
int tid;
tid = *((int *) x);
printf("Hi from thread %d!\n", tid);
#pragma omp parallel
{
int n = omp_get_num_threads();
#pragma omp master
printf("num threads: %d\n", n);
#pragma omp for
for( int i=0; i < n; i++) {
int t = omp_get_thread_num();
printf("I'm thread %d-%d!\n", tid, t );
}
}
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 0;
}
@yohm
Copy link
Author

yohm commented Apr 13, 2016

Testing Environment: MacOSX ElCapitan

When I use g++-4.9 installed via homebrew, I got SEGV as follows.

spawning thread 0
spawning thread 1
Hi from thread 0!
spawning thread 2
Hi from thread 1!
zsh: segmentation fault  ./a.out

However, if I use g++-5, pthread and OpenMP coexists well.

spawning thread 0
spawning thread 1
Hi from thread 0!
spawning thread 2
Hi from thread 1!
spawning thread 3
Hi from thread 2!
Hi from thread 3!
I'm thread 2-1!
I'm thread 2-2!
num threads: 4
I'm thread 2-3!
I'm thread 0-1!
I'm thread 0-2!
num threads: 4
I'm thread 2-0!
I'm thread 0-3!
I'm thread 1-2!
num threads: 4
I'm thread 1-1!
I'm thread 1-3!
I'm thread 3-2!
I'm thread 3-1!
num threads: 4
I'm thread 3-3!
I'm thread 0-0!
I'm thread 1-0!
I'm thread 3-0!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment