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

question on pthread_join() and pthread_detach()

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

Thread 1 created Thread 2 created test3

虽然我认为应该是

thread 1 created test2 thread 2 created test3 test1 顺序可能会改变,但我应该有这一行,所以为什么它会转义这个打印语句?

#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);

您正在尝试使用指针 return 调用 pthread_create(),方法是在新线程中调用 function() 作为 运行 的函数(记住,函数参数在函数本身被调用之前得到评估)。现在, function() 实际上 return 没有任何值,但它在其主体中调用 function2() (同时评估另一个调用的参数 pthread_create()),没有return任何值,但是确实调用了pthread_exit()。由于此时只有一个线程,因为只有主进程线程是 运行ning(pthread_create() 还没有真正被调用;调用堆栈看起来像 main() -> function() -> function2()),整个程序然后退出。

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

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

等等