1 libc的缓冲地位
如图,如果调用printf之类的库函数,数据会先进入库缓冲区,然后在一定条件下(满足库定义的条件或主动调用fflush),才会写入操作系统缓冲区。
如果直接调用write系统函数,就会直接写入操作系统缓冲区,所以在即使在单线程的情况下,如果混用printf和write,也可能会有“时序错乱”问题,即后面的语句先输出的问题。可以参看我之前一篇文章。
2 多线程下的printf
其实printf是否是线程安全(thread-safe)的,这要看具体的库实现,某些是,某些不是。
因为printf要使用到全局变量stdout,以及动态分配内存时要用到地址表,所以肯定不是可重入(reentrant)的,不可以在信号处理函数中调用printf。
GNU版本的glibc的实现是线程安全的,即每一次printf可以看做是原子的,但是多线程会产生交错,如果想同步,可以使用flockfile/funlockfile来锁定和解锁FILE*变量。[1]
3 一个实例
我写了如下代码:
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
char buf[64];
tid = (long)threadid;
// size_t len = snprintf( buf, sizeof(buf), "Hello World! It's me, thread #%ld!\n", tid );
// write( fileno(stdout), buf, len );
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
// pthread_exit(NULL);
return 0;
}
因为在main中注释掉了pthread_exit,所以main返回时,其它线程也会结束。执行结果有以下两个情况比较诡异:
In main: creating thread 0
In main: creating thread 1
Hello World! It's me, thread #0!
In main: creating thread 2
Hello World! It's me, thread #1!
In main: creating thread 3
Hello World! It's me, thread #2!
In main: creating thread 4
Hello World! It's me, thread #3!
Hello World! It's me, thread #3!
In main: creating thread 0
In main: creating thread 1
Hello World! It's me, thread #0!
In main: creating thread 2
Hello World! It's me, thread #1!
In main: creating thread 3
Hello World! It's me, thread #2!
In main: creating thread 4
Hello World! It's me, thread #3!
Hello World! It's me, thread #4!
Hello World! It's me, thread #4!
一个是线程3打印了2次,一个是线程4打印了2次。
分析可能是如下原因:
一个printf流程可能是先把数据写入库缓冲区,然后更新缓冲区大小(增加)。在写入操作系统(调用write)后(时间点A),再次更新缓冲区大小(减少)。然而可能进程结束的时候,某一个线程执行到了时间点A就被强制结束了,所以库并没有意识到已经成功输出了,会在进程退出清理库空间的时候又一次输出。
4 结论
多线程下最好不要用printf,用snprintf和write会更好。
参考
[1] http://stackoverflow.com/questions/467938/stdout-thread-safe-in-c-on-linux