c - 关于 pthread_join() 和 pthread_detach() 的问题

标签 c pthreads

我写这个程序是为了练习 pthread 系统调用,所以我使用了一些打印行来检查结果,但是它们被转义了,输出是:

线程 1 已创建 线程 2 已创建 测试3

虽然我觉得应该是

线程 1 已创建 测试2 线程 2 创建 测试3 测试1 顺序可能会改变,但我应该有这一行,所以为什么它会转义这个打印语句?

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



void *function();
void *function2();




int main(int argc, char *argv[])
{
    pthread_t tid;
    int rc;
    rc = pthread_create(&tid, NULL, function(), NULL);
    if(rc > 0){
        fprintf(stderr, "Error\n");
        exit(1);
    }
    pthread_join(tid, NULL);
    sleep(1);
    printf("test1\n");
    pthread_exit(NULL);
}

void *function(){
    int rc;
    pthread_t tid;
    printf("Thread 1 created\n");
    rc = pthread_create(&tid, NULL, function2(), NULL);
    if(rc > 0){
        fprintf(stderr, "Error\n");
        exit(1);
    }
    printf("test2\n");
    pthread_exit(NULL);
}

void *function2(){
    pthread_detach(pthread_self());
    printf("Thread 2 created\n");
    printf("test3\n");
    pthread_exit(NULL);
}

最佳答案

rc = pthread_create(&tid, NULL, function(), NULL);

您正在尝试使用通过调用 function() 返回的指针调用 pthread_create() 作为在新线程中运行的函数(记住,函数参数获取在调用函数本身之前进行评估)。现在,function() 实际上并不返回任何值,但它在其主体中调用了 function2()(同时评估另一个参数调用 pthread_create()),不返回任何值,但确实调用了 pthread_exit()反而。由于此时只有一个线程,因为只有主进程线程在运行(pthread_create() 尚未实际调用;调用堆栈看起来像 main() -> function( ) -> function2()), 然后整个程序退出。

您需要使用指向 functionfunction2 的指针来调用 pthread_create(),而不是调用它们的结果:

rc = pthread_create(&tid, NULL, function, NULL);

等等

关于c - 关于 pthread_join() 和 pthread_detach() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53807512/

相关文章:

objective-c - 如何为 iOS 5 编译 Rabbitmq-c 库?

c - 结构体中指针的大小

c - 访问不同 c 文件中 pthread 中的全局变量

释放后检查结构体是否释放

c - 可以在 C 中返回和释放动态分配的数组吗?

c - stm32f103c8t6上TIM2_CH1有问题

c - 我的遗传算法 C 代码不起作用,它不进入 if 条件

linux - SCHED_FIFO 线程在 Linux 中被 SCHED_OTHER 线程抢占

c - 线程终止问题(C 编程)

c - Linux线程优先级