c多线程的奇怪问题,大家来讨论讨论
这样一个程序,期望的输出应该是:start to create thread
good bady
还应该有一句hello everybody,但输出的结果没有最后一句。
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<pthread.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/time.h>
void *hello();
main(){
pthread_t t;
char *x="hello world";
printf("start to create a thread\n");
if(pthread_create(&t,NULL,(void*)hello,NULL)!=0){
printf("error in create thread\n");
exit(1);
}
printf("good baby!\n");
exit(1);
}
void *hello(){
printf("hello everybody\n");
pthread_exit(0);
}
后来我在printf("good baby!\n");前加了hello();一句。结果输出了两个hello everybody(正常的也是输出两次)。奇怪的是第一次为什么没输出helloeverybody呢?是语言问题还是机器问题?系统是linux 企业版,版本忘了
参考答案:线程创建成功后
加一句
sleep(1);
或
pthread_yield();
就可以了
看不到结果的原因是,你创建的线程还没有开始执行,主线程就直接执行完毕了。主线程执行则导致程序马上退出。