繁体   English   中英

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-您好\\ n

2- Helle \\ n您好\\ n

3-您好\\ n您好\\ n您好\\ n

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

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

也许您正在寻找pthread_barrier_wait

链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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