我遇到了 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,因此不应受其代码影响。
最佳答案
这与线程无关。
你会发现同样的行为发生在:
printf("Doing something");
while(1) ;
这是因为您没有在打印的字符串末尾包含换行符,这导致该行被缓冲。由于没有进一步的输出生成,该行可能会缓冲很长时间(甚至可能永远)。
为避免这种情况,您可以:
向所有输出行添加换行符,例如
printf("做某事\n");
在
printf()
之后调用fflush(stdout)
强制刷新行预先调用
setvbuf(stdout, NULL, _IONBF, 0)
以禁用所有输出缓冲
关于创建的线程很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43811550/