我正在编写一个多线程程序。程序结构如下所示
int main()
{
printf("To Call threads\n");
thread1=pthread_create(&trd1,NULL,process1,(void *)sleepTimeForP1);
thread2=pthread_create(&trd2,NULL,process2,(void *)sleepTimeForP2);
pthread_join(trd1, NULL);
pthread_join(trd2, NULL);
return 0;
}
线程的代码是
void *process1 (void *sleepTimeForP1)
{
int *tsleepTimeForP1 = (int *)sleepTimeForP1;
while(1)
{
pthread_mutex_lock(&lock);
printf("inside thread\n");
pthread_mutex_unlock(&lock);
sleep(1);
}
}
该代码工作正常,并在未完成输出重定向时打印输出。但是当给出输出重定向时,文件中没有输出。现在,如果我在每个 printf()
语句之后给出显式 fflush(stdout)
,我就会得到所需的输出。为什么我需要给出明确的 fflush() ?
最佳答案
来自 C99 §7.19.3[7]:
As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.
“完全缓冲”(相对于“行缓冲”):C99 §7.19.3[3]
When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered.
因此,当标准输出是交互式的(例如 shell)时,它是行缓冲的。但是,当您将它重定向到一个文件时,它会变成完全缓冲的,您必须使用 fflush
。
关于c - 除非在使用输出重定向时调用显式 fflush 函数,否则线程不会给出输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32071041/