简体   繁体   English

使用pthread_exit和pthread_join。 pthread_exit不会终止调用函数

[英]using pthread_exit and pthread_join. pthread_exit doesn't terminate the calling function

gcc 4.6.0 c89 gcc 4.6.0 c89

I am just experimenting with using pthread_exit and pthread_join. 我只是在尝试使用pthread_exit和pthread_join。

The only thing I notice with the pthread_exit it that it didn't display the print message before main returned. 我用pthread_exit注意到的唯一一件事是,在main返回之前它没有显示打印消息。 However, pthread_join did exactly that. 但是,pthread_join确实做到了这一点。

I would have thought the print statement should have been displayed. 我本以为应该显示打印声明。 If not does that mean that main has not terminated correctly in using the pthread_exit? 如果不是,则表示main在使用pthread_exit时未正确终止?

Many thanks for any suggestions, 非常感谢您的任何建议,

My source code snippet source.c file: 我的源代码片段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;
}

Source code snippet main.c file: 源代码段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;
}

What you're seeing is expected. 您所看到的是预期的。 pthread_exit never returns. pthread_exit 永不返回。 It stops the thread that calls it immediately (and then runs the clean-up handlers if any, and then potentially thread-specific data destructors). 它停止立即调用它的线程(然后运行清理处理程序(如果有),然后运行潜在于线程的数据析构函数)。

Nothing in main after pthread_exit will ever run. pthread_exit之后的main都不会运行。

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

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