C - 等待多个线程终止

时间:2015-03-07 13:59:03

标签: c multithreading pthreads 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- Helle \ nHello \ n

3-你好\ nHello \ nHello \ n

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

2 个答案:

答案 0 :(得分:1)

在每种情况下,您都希望&mapperThreads[i]代替&mapperThreads[N]

答案 1 :(得分:0)

也许pthread_barrier_wait是您正在寻找的?

Link