在 Linux 中的不同线程之间缓冲 `printf` 输出 [英] Buffering `printf` outputs between different threads in Linux

查看:45
本文介绍了在 Linux 中的不同线程之间缓冲 `printf` 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>

pthread_t ntid;void
printids(const char *s) {
  printf("%s \n", s);
}

void *
thr_fn(void *arg)   {
  printids("new thread: ");
  return((void *)0);
}

int
main(void)  {
  pthread_create(&ntid, NULL, thr_fn, NULL);
  printids("main thread:");
}

我在 Red Hat Enterprise Linux Workstation 6.5 版上运行它.
这是我的编译命令

I'm running it on Red Hat Enterprise Linux Workstation release 6.5 .
Here is my compiling command

gcc -ansi -g -std=c99 -Wall -DLINUX -D_GNU_SOURCE threadid.c -o threadid -pthread -lrt -lbsd

gcc -ansi -g -std=c99 -Wall -DLINUX -D_GNU_SOURCE threadid.c -o threadid -pthread -lrt -lbsd

输出如下:

主线程:
新线程:
新话题:

main thread:
new thread:
new thread:

为什么新线程"被打印了两次?我怀疑这可能与 Linux 中的缓冲机制有关.但是在我在每个函数的末尾添加了 fflush(stdout)fsync(1) 之后.输出几乎相同.

Why "new thread" has been printed twice? I doubt this may related to buffering mechanism in Linux. But after I added fflush(stdout) and fsync(1) in the end of each function. The output is almost the same.

如果您多次运行该程序.输出不同:

If you run the program several times. The output differs:

主线程:
新话题:

main thread:
new thread:

主线程:
新线程:
新话题:

main thread:
new thread:
new thread:

主线程:

推荐答案

大多数 libc 库确实像您提到的那样缓冲输出.并且在程序结束时(当主线程退出时),它们会刷新所有缓冲区并退出.

Most libc libraries do buffer the output as you mentioned. And at the end of the program (when the main thread exits), they flush all the buffers and exit.

您的新线程可能已经刷新了输出,但在它可以更新缓冲区的状态之前,主程序退出并且清理代码再次刷新了相同的缓冲区.由于这些缓冲区对于线程来说是本地的,我确信它们不会有并发机制.但由于这种罕见的情况,它可能会被搞砸.

There is a slight possibility that your new thread has flushed the output but before it could update the state of the buffer, the main program exited and the cleanup code flushed the same buffer again. Since these buffers are local to the thread I am sure they won't have concurrency mechanism. But because of this rare case it might get messed up.

你可以试试

err = pthread_create(&ntid, NULL, thr_fn, NULL);
printids("main thread:");
pthread_join(ntid, NULL);

在main函数的最后,检查问题是否解决.

At the end of the main function and check if the problem is solved.

这将导致您的主函数等待新线程完成(包括它所做的刷新操作).

This will cause your main function to wait till the new thread is finished (including the flushing operation it does).

这篇关于在 Linux 中的不同线程之间缓冲 `printf` 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆