1:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<errno.h>
void * thread1(void *arg)
{
printf("Hi\n");
}
void * thread2(void *arg)
{
sleep(1);
printf("are you\n");
}
void * thread3(void *arg)
{
sleep(2);
printf("I am pretty good!\n");
}
int main(int argc,char *argv[])
{
pthread_t tid1,tid2,tid3;
if(pthread_create(&tid1,NULL,thread1,NULL) != 0) {
perror("pthread_create");
}
if(pthread_create(&tid2,NULL,thread2,NULL) != 0) {
perror("pthread_create");
}
if(pthread_create(&tid3,NULL,thread3,NULL) != 0) {
perror("pthread_create");
}
//printf("\n"); //如果加入这句就正常了
return 0;
}
2:我的主线程
没有等待任何子线程
,但是现在的执行结果无论如何也不应该像下面这样,把 Hi
输出两次。
3::
1) 主线程在子线程执行前关闭了,这个程序就crash了。
2) 我建议你把t2 t3都注释掉,这样肯定不会打印两次。
3) 正确的
join/detach
线程也不会出现这样的结果。