简体   繁体   English

C-等待多个线程终止

[英]C - Waiting For Multiple Threads to Terminate

I am trying to wait for all the threads to terminate before the main() process terminates. 我试图等待所有线程在main()进程终止之前终止。 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 1-您好\\ n

2- Helle\\nHello\\n 2- Helle \\ n您好\\ n

3- Hello\\nHello\\nHello\\n 3-您好\\ n您好\\ n您好\\ n

It looks like the main() process does not always wait for all threads to terminate. 看起来main()进程并不总是等待所有线程终止。 What am I doing wrong? 我究竟做错了什么?

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

Maybe pthread_barrier_wait is what you're looking for ? 也许您正在寻找pthread_barrier_wait

Link 链接

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

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