我写这个程序是为了练习 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()
), 然后整个程序退出。
您需要使用指向 function
和 function2
的指针来调用 pthread_create()
,而不是调用它们的结果:
rc = pthread_create(&tid, NULL, function, NULL);
等等
关于c - 关于 pthread_join() 和 pthread_detach() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53807512/