I am trying to wait for all the threads to terminate before the main() process terminates. Here is what I have so far:
void* mapperFunction()
{
printf("Hello\n");
return NULL;
}
int main()
{
int i; // Used in "for" loops.
int N = 3;
pthread_t* mapperThreads = (pthread_t*) malloc(sizeof(pthread_t) * N);
for ( i = 0; i < N; i++)
{ // Creates all the mapper threads.
pthread_create( &mapperThreads[N], NULL, mapperFunction, NULL);
}
for ( i = 0; i < N; i++)
{ // Waits for all the mapper threads to terminate.
pthread_join( mapperThreads[N],NULL);
}
return 0;
}
I get three different outputs when I run this code;
1- Hello\n
2- Helle\nHello\n
3- Hello\nHello\nHello\n
It looks like the main() process does not always wait for all threads to terminate. What am I doing wrong?
You want &mapperThreads[i]
instead of &mapperThreads[N]
in each case.