#include <stdio.h>
#include <pthread.h>
void *Thread1 (void)
{
while (1){
printf("this is thread1!!\n");
sleep(5);
}
}
void *Thread2 (void)
{
while (1){
printf("this is thread2!!\n");
sleep(10);
}
}
int main()
{
pthread_t thread1_td,thread2_td;
pthread_create(&thread1_td,NULL,(void*)Thread1,NULL);
pthread_create(&thread2_td,NULL,(void*)Thread2,NULL);
while (1)
{
printf("this is main!!!\n");
sleep(2);
};
return 0;
}
初学者一枚,在学习编写线程文件时,使用了printf函数,但是结果却不打印出来,好像陷入一个死循环里面。后来发现是printf函数的问题。
printf("this is main!!!");
printf("this is main!!!\n");
这两个printf只相差了一个\n,前者没有结果打印出来,后者有结果打印出来。
学过C的人都知道\n是回车符的意思,按照我们的理解,有无\n也就只影响打印出来的效果
例如(让以上的代码处于循环打印的过程):
前者:
this is main!!!this is main!!!this is main!!!this is main!!!
后者:
this is main!!!
this is main!!!
this is main!!!
应该是不会影响信息的输出的,可是这却发生了。
实在是让人费解。
对了,由于pthread库不在linux的系统库中,所以我们在编译的时候要用 gcc test.c -o test -lpthread (PS:这里lpthread的大写为LPTHREAD,所以开头是L不是I。不要混淆了)