C - 等待多个线程终止

C - Waiting For Multiple Threads to Terminate

我正在尝试等待所有线程在 main() 进程终止之前终止。这是我目前所拥有的:

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;
}

当我 运行 这段代码时,我得到三个不同的输出;

1- Hello\n

2- 赫勒\nHello\n

3- Hello\nHello\nHello\n

看起来 main() 进程并不总是等待所有线程终止。我做错了什么?

也许 pthread_barrier_wait 就是您要找的东西?

Link

在每种情况下,您都需要 &mapperThreads[i] 而不是 &mapperThreads[N]