c - 这是 printf()/pthread 错误,还是我遗漏了什么?

标签 c pthreads printf mutex

我最近努力学习多线程,但遇到了以下意想不到的行为 - 至少对我来说是这样:在以下非常简单的代码中调用 printf 时,一次不会打印超过一行:

    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
    char buffer[2];

    void * thread_routine(void * args){
      pthread_mutex_lock(&mutex);
      pthread_cond_wait(&cond, &mutex);
      printf("test %s\n test\n", buffer);
      pthread_mutex_unlock(&mutex);
      return(NULL);
    }

    int main(void){
      pthread_t thread;
      pthread_create(&thread, NULL, thread_routine, NULL);
      sleep(1);
      buffer[0] = 'c';
      buffer[1] = '\0';
      pthread_mutex_lock(&mutex);
      pthread_cond_signal(&cond);
      pthread_mutex_unlock(&mutex);
      sleep(10);
      return(0);
    }

输出为

    test c

(等待 10 秒)

    test prompt$]

这段代码有什么问题?为什么我不能让 printf 一次打印两行?请注意,使用flockfile阻止stdout并使用funlockfile解锁并不能改善这种情况。

最佳答案

如果你的程序如你所说在最后打印了测试提示$],这意味着你执行的版本在“test %s\n”中没有第二个换行符测试\n"

换行符很重要,因为这是输出刷新到屏幕的时候。请参阅Why does printf not flush after the call unless a newline is in the format string?以获得解释和建议。

尝试重新编译并重新运行您问题中的确切代码,我打赌它会按预期工作(在我的盒子上肯定会这样)。

关于c - 这是 printf()/pthread 错误,还是我遗漏了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806085/

相关文章:

c - 简单程序将 "D"添加到输出

c - Eclipse 构建的二进制文件太重

c - 为什么 'extern'存储类的功能不同?

c - 为什么 gcc 忽略 __attribute__((stdcall))?

c - 读取 popen() 时如何修复 fgets() 挂起?

c - 不正确的方法签名和调用

c - strcmp 是线程安全的吗?

c++ - 如何在pthread线程中创建memcpy?

printf - 未解析的外部符号 __stdio_common_vswprintf

c - printf 字符打印的意外结果