我编写了这个程序来练习 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);
您正在尝试pthread_create()
使用function()
作为在新线程中运行的函数调用返回的指针进行调用(请记住,函数参数在调用函数本身之前得到评估)。现在,function()
实际上并不返回任何值,但是它呼吁function2()
在它的身上(而评估的参数再调用pthread_create()
),它也不会返回任何值,但不会打电话pthread_exit()
来代替。由于此时只有一个线程,因为只有主进程线程在运行(pthread_create()
实际上还没有被调用;调用堆栈看起来像main() -> function() -> function2()
),整个程序然后退出。
您需要pthread_create()
使用指向function
and 的指针进行调用,而function2
不是调用它们的结果:
rc = pthread_create(&tid, NULL, function, NULL);
等等。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句