OS X上的fprintf线程安全吗?

时间:2010-02-02 22:37:47

标签: macos thread-safety printf

OS X上的fprintf线程安全吗?如果是这样,这会记录在哪里?

2 个答案:

答案 0 :(得分:5)

OS X符合的POSIX线程规范(AKA Pthreads)要求stdio函数是线程安全的。它还提供flockfilefunlockfile函数,以确保其他线程在锁定时不能在FILE *上交错I / O.

请参阅http://pubs.opengroup.org/onlinepubs/007908799/xsh/threads.html,特别是标题为“线程安全”的部分。

答案 1 :(得分:3)

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

THINK fprintf()在OSX上是线程安全的。我的第一个原因是达尔文人正朝着这个方向前进,这可以从他们选择放弃旧学校的全球“错误”以支持函数errno()来证明。有关文档,请按照'/usr/include/errno.h'进行操作。没有它,libc的东西都不是线程安全的。然而,使用errno()函数并不能证明fprintf()。这只是一个开始。我敢肯定每个人都知道至少有一种情况,苹果没有带来好主意。

我相信fprintf()的'线程安全'的另一个原因是source code,它应该是'真实的',至少在Apple关闭(部分/全部)时为10.6 OSX。扫描该代码为“MT-Safe”,您将看到 CLAIM ,即“vfprintf()”的非语言环境版本是线程安全的。同样,这并不能证明什么。然而,它是一种你想要的文档形式。

我认为fprintf()是线程安全的最终理由是一个测试用例。这也不是什么大事。也许它证明缓冲区空间是线程安全的。好吧,这是写一个有趣的小程序的借口。实际上,我没有写它。我在网上发现了一个骨架,并进行了修改。 “FLUSH_BUFFER”定义可让您更清楚地了解正在发生的事情。如果没有定义该宏,则会得到'sort-of'缓冲区测试(没有一些行终止符的相同文本)。我无法找到一种方法来安排更有意义的线程冲突。

我猜你可能会写到多个文件。写入单个文件可能是一个更好的测试。附加的程序不是一个明确的测试。虽然它可以扩展,但我不确定任何程序是否真的可以确定。一句话:也许你应该只调用你对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);
}