2010-02-02 94 views

回答

3

这是一个很好的问题,虽然类似的问题已经在这里被问过很多次。我对OSX方面很感兴趣,因为我试图在自己的系统上加快速度。 (也许你应该添加OSX标签)

想想 fprintf()在OSX上是线程安全的。我的第一个原因是,达尔文人正朝着这个方向前进,证明他们选择放弃旧式全球“errno”而转而使用errno()函数。对于文档,只需按照'/usr/include/errno.h'。没有这些,没有任何libc的东西会是线程安全的。然而,使用errno()函数并不能证明fprintf()的任何内容。这只是一个开始。我相信每个人都知道至少有一种情况苹果没有一个好主意。

我相信fprintf()的'线程安全性'的另一个原因是source code,它应该是'真实的',至少在Apple关闭(部分/全部)OSX的10.6之前。扫描该代码以获得“MT-Safe”,并且您将看到一个CLAIM,'vfprintf()'的非本地版本是线程安全的。再次,这没有任何证据。但它是一种你想要的文档形式。

我相信fprintf()是线程安全的最终原因是测试用例。这也没有证明任何东西。也许它证明了缓冲区空间是线程安全的。好吧,这是写一个有趣的小程序的借口。其实,我没有写。我在网上找到了一个骨架,并对其进行了修改“FLUSH_BUFFER”定义允许您更清楚地看到发生了什么。如果这个宏没有定义,你会得到'排序'缓冲区测试(同样的文本没有一些行终止符)。我找不出一种方法来安排更有意义的线程冲突。

我猜你可能会写入多个文件。写入单个文件可能是一个更好的测试。附加的程序不是一个明确的测试。尽管可以扩展,但我不确定任何程序是否可以确定。底线:也许你应该只是MUTEX你的电话fprintf()。

// artificial test for thread safety of fprintf() 
// define FLUSH_BUFFER to get a good picture of what's happening, un-def for a buffer test 
// the 'pretty print' (FLUSH_BUFFER) output relies on a mono-spaced font 
// a writeable file name on the command line will send output to that file 
// 

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

#define FLUSH_BUFFER 

#define NTHREAD  5 
#define ITERATIONS 3 

const char DOTS[] = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . "; 
FILE *outFile; 

void *PrintHello(void *threadid) { 
    long tid; 

    tid = (long)threadid; 
    for (int i=1; i<=ITERATIONS; i++) { 
     long delay = (NTHREAD-tid) * 100000 + (ITERATIONS-i+1) * 10000; 
#ifdef FLUSH_BUFFER 
     fprintf(outFile, "%*sStart thread %d iteration %d\n", (tid+1)*4, " ", tid, i); 
     usleep(delay); 
     fprintf(outFile, "%*sFinish thread %d iteration %d %*.*sw/delay %d\n", 
       (tid+1)*4, " ", tid, i, (NTHREAD-tid+1)*4, (NTHREAD-tid+1)*4, DOTS, delay); 
#else 
     fprintf(outFile, "Start thread %d iteration %d ", tid, i); 
     usleep(delay); 
     fprintf(outFile, "Finish thread %d iteration %d w/delay %d\n", tid, i, delay); 
#endif 
    } 
    pthread_exit(NULL); 
} 

int main (int argc, char *argv[]) { 
    pthread_t threads[NTHREAD]; 
    char errStr[100]; 
    int rc; 
    long t; 

    if(argc > 1) { 
     if(! (outFile = fopen(argv[1], "w"))) { 
      perror(argv[1]); 
      exit(1); 
     } 
    } else 
     outFile = stdout; 

    for(t=0; t<NTHREAD; t++) { 
     fprintf(outFile, "In main: creating thread %ld\n", t); 
     if(rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t)) { 
      sprintf(errStr, "ERROR; pthread_create() returned %d", rc); 
      perror(errStr); 
      exit(2); 
     } 
    } 
    pthread_exit(NULL); 
}