【问题标题】:Questions on pthread_join() and pthread_create()关于 pthread_join() 和 pthread_create() 的问题
【发布时间】:2016-10-04 07:14:23
【问题描述】:

这是 pthread_create 的声明:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *  
          (*start_routine) (void *), void *arg);

它包含一个函数 start_routine。

所以当我们调用 pthread_create 时,该函数将使用参数 arg 执行。
那为什么要调用 pthread_join(),因为要执行 start_routine 函数?
我也尝试不包含 pthread_join( ) 函数,确实 start_routine 函数根本没有执行,进程创建后就退出了。
那么当程序来到 pthread_create 时,它​​究竟会发生什么?参数 start_routine 的执行是否有条件?
令人困惑... 这是我的测试代码:

#include <pthread.h>
#include <stdio.h>
int sum;
void* runner(void *param);

int main(int argc, char *argv[])
{
    pthread_t tid; //The thread identifier
    pthread_attr_t attr;//set of thread attributes

    if(argc!=2){
    fprintf(stderr, "usage:a.out <integer value>\n");
    return -1;
    }
    if(atoi(argv[1])<0){
    fprintf(stderr, "%d must be <=0\n",atoi(argv[1]));
    return -1;
    }


    //get the default attributes
    pthread_attr_init(&attr);
    //create the thread
    pthread_create(&tid,&attr,runner,argv[1]);
    //now wait for the thread to exit
    pthread_join(tid,NULL);

    printf("sum=%d\n", sum);
}

    void* runner(void *param)
    {
        int i,upper = atoi(param);
        sum=0;

        for(i=1;i<=upper;i++)
            sum+=i;

        pthread_exit(0);
    }

【问题讨论】:

    标签: linux process pthread-join


    【解决方案1】:
    1. 通常会调用您的例程。如果它无事可做并退出,你的线程生命就完成了。
    2. 您的 start_routine() 是否有任何代码/打印语句可用于验证/调试其功能?
    3. 不需要调用 pthread_join()。如果您想在 start_routine() 完成/终止其执行(内部/外部)后等待它,它将是必需的。并检查线程函数的返回状态。
    4. 线程不运行的其他情况可能是:系统内存非常低或现有线程(及其优先级)过多地占用系统以致它没有任何运行机会。
    5. 您是否还检查了 pthread_create() 中的错误代码?

    如果您可以共享您的测试代码,包括 pthread_create() 和 start_routine() 的调用者,将会有所帮助。

    【讨论】:

    • 谢谢!我分享了我的测试代码,我确实想等待总和计算。我只是想知道创建如何知道我是否包含连接功能?难道不应该让跑步者毫无例外地计算吗?如果我取消join函数,sum确实会保持为0,也就是说create函数没有执行runner来计算,这和join函数有关吧?
    【解决方案2】:

    如果您在 pthread_join 之前退出应用程序或进程,该进程将不会等待 start_routine 应用程序完成执行。它只会杀死线程以及所有资源

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      相关资源
      最近更新 更多