pthread_join()意外结果

时间:2014-11-12 18:56:56

标签: c multithreading pthreads pthread-join

由于我得到的结果,我无法理解pthread_join()函数。

如果pthread_join()应该暂停调用线程,直到给定线程id的线程完成它的工作,那么为什么以下代码不执行线程1 然后执行线程2 工作。它们同时发生。

如果我取出两条pthread_join()行(来自main),程序将终止并且没有任何反应。这是否意味着主线程是两个连接函数的调用进程,而主线程是否正在等待其他两个新创建的线程完成?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *functionCount1();
void *functionCount2(void*);

int main()
{

    /* 
        How to Compile
         gcc -c foo
         gcc -pthread -o foo foo.o
    */

    printf("\n\n");

    int rc;
    pthread_t thread1, thread2;

    /* Create two thread --I took out error checking for clarity*/
    pthread_create( &thread1, NULL, &functionCount1, NULL)
    pthread_create( &thread2, NULL, &functionCount2, &thread1)

    pthread_join( thread1, NULL);
    pthread_join( thread2, NULL);

    printf("\n\n");
    exit(0);
}

void *functionCount1()
{

    printf("\nFunction 1");
        sleep(5);
    printf("\nFunction 1");

    return(NULL);
}

void *functionCount2(void* argument)
{

    //pthread_t* threadID = (pthread_t*) argument;

    //pthread_join(*threadID, NULL);

    printf("\nFunction 2");
        sleep(5);
    printf("\nFunction 2");

    return(NULL);
}

输出:

enter image description here

sleep输出已注释掉:

enter image description here

有人可以解释为什么pthread_join没有做文档让你相信的事情吗?

1 个答案:

答案 0 :(得分:3)

  

如果pthread_join()应暂停调用进程,直到给定线程ID的线程完成它的工作...

这不太正确:pthread_join()应该暂停调用线程,而不是调用进程。由于您从运行pthread_join()函数的线程调用main,因此允许其他两个线程同时进行,即它们在您的示例中的方式。

您注释掉的代码不起作用的原因是您正在向pthread_t传递指针,但是您将其转换为线程运行函数内的普通pthread_t(即{{1变成pthread_t*)。修复此问题应该允许您的代码生成您期望的结果:

pthread_t

此外,您应该从void *functionCount2(void* argument) { pthread_t *threadID = (pthread_t*) argument; pthread_join(*threadID, NULL); printf("\nFunction 2"); sleep(5); printf("\nFunction 2"); return(NULL); } 函数中删除pthread_join( thread1, NULL);,因为指定同一目标线程的多个main同时调用的结果未定义。