我遇到了奇怪的行为pthread_create
函数。代码如下:创建线程很慢
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
void *foo(void* a) {
printf("Doing something");
pthread_exit(NULL);
}
int main() {
printf("Main created");
pthread_t thread;
pthread_create(&thread, NULL, foo, NULL);
while(1); // This causes trouble
pthread_join(thread, NULL);
return 0;
}
出于某种原因,在地方while
,从跟帖留言很长的延迟后显示。我希望在pthread_create之后调用新线程是完全独立于main的,因此不应该被它的代码所影响。
您是否尝试刷新'stdout'? –
@BenSteffan谢谢你的评论,在这个例子中它是由输出缓冲引起的。 – Lorin
对'printf()'的调用正在写入'stdout'流缓冲区。要通过该缓冲区并显示在终端上,必须发生以下三件事之一。 1)缓冲区溢出(不太可能)2)程序结束3)格式字符串或数据以'\ n'结尾(未完成)因此在程序结束之前不会输出任何内容。 'while(1);'循环永远不会退出,所以程序永远不会结束。还要注意:'main()'会吸收所有循环的CPU周期,所以没有任何东西可以让创建的线程运行。建议:使用'\ n'结束每个'printf()'格式字符串并移除'while()'语句 – user3629249