【问题标题】:using pthread_exit and pthread_join. pthread_exit doesn't terminate the calling function使用 pthread_exit 和 pthread_join。 pthread_exit 不会终止调用函数
【发布时间】:2011-04-24 08:58:12
【问题描述】:

gcc 4.6.0 c89

我只是在尝试使用 pthread_exit 和 pthread_join。

我注意到 pthread_exit 的唯一一件事是它在 main 返回之前没有显示打印消息。然而,pthread_join 正是这样做的。

我原以为应该显示打印语句。如果不是,这是否意味着 main 在使用 pthread_exit 时没有正确终止?

非常感谢您的任何建议,

我的源代码sn -p source.c文件:

void* process_events(void)
{
    app_running = TRUE;
    int counter = 0;

    while(app_running) {
#define TIMEOUT 3000000
        printf("Sleeping.....\n");
        usleep(TIMEOUT);

        if(counter++ == 2) {
            app_running = FALSE;
        }
    }

    printf("Finished process events\n");

    return NULL;
}

源码sn -p main.c文件:

int main(void)
{
    pthread_t th_id = 0;
    int th_rc = 0;

    th_rc = pthread_create(&th_id, NULL, (void*)process_events, NULL);
    if(th_rc == -1) {
        fprintf(stderr, "Cannot create thread [ %s ]\n", strerror(errno));
        return -1;
    }

    /*
     * Test with pthread_exit and pthread_join
     */

    /* pthread_exit(NULL); */

    if(pthread_join(th_id, NULL) == -1) {
        fprintf(stderr, "Failed to join thread [ %s ]", strerror(errno));
        return -1;
    }

    printf("Program Terminated\n");

    return 0;
}

【问题讨论】:

    标签: c pthreads


    【解决方案1】:

    您所看到的是预期的。 pthread_exit 从不返回。它立即停止调用它的线程(然后运行清理处理程序(如果有),然后可能是线程特定的数据析构函数)。

    pthread_exit 之后的 main 中的任何内容都不会运行。

    【讨论】:

    • 你好垫子,谢谢你的回答。我想如果你想运行任何任务,应该在调用 pthread_exit 之前完成。
    • pthread_exit 不会运行退出处理程序,除非它导致整个进程退出(由于最后一个线程的终止)。它确实运行取消清理处理程序和线程特定数据析构函数。
    猜你喜欢
    • 2012-01-20
    • 2015-01-29
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2014-12-11
    相关资源
    最近更新 更多