简体   繁体   中英

C - Waiting For Multiple Threads to Terminate

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?

在每种情况下,您都希望使用&mapperThreads[i]而不是&mapperThreads[N]

Maybe pthread_barrier_wait is what you're looking for ?

Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM