C++ 打印/cout 在多线程中重叠?

标签 c++ multithreading printing cout

我想知道如何在使用多线程时处理打印。
我认为这会很简单:

#include <iostream>
#include <pthread.h>
using namespace std;

bool printing = false;

struct argumentStruct {
    int a;
    float b;
};

void *ThreadFunction(void *arguments) {
  struct argumentStruct*args = (struct argumentStruct*)arguments;
  int a = args->a;
  float b = args->b;
    while (printing) {}
    printing = true;
      cout << "Some text...." << a << b << endl;
    printing = false;
}

main() {
    pthread_t threads[3];
    struct argumentStruct argStruct[3];

    argStruct[0].a = 1;
    argStruct[0].b = 1.1;
    pthread_create(&threads[0], NULL, &ThreadFunction, (void *)&argStruct[0]);

    argStruct[1].a = 2;
    argStruct[1].b = 2.2;
    pthread_create(&threads[1], NULL, &ThreadFunction, (void *)&argStruct[1]);

    argStruct[2]a = 3;
    argStruct[2].b = 3.3;
    pthread_create(&threads[2], NULL, &ThreadFunction, (void *)&argStruct[2]);

    getchar();
    return 0;
}

但这并不能很好地工作。一些 cout 被跳过(或者可能被覆盖?)。
那我做错了什么?我该如何正确处理这个问题?

最佳答案

问题在于测试和设置 printing 变量的语句不是原子,即它们不会在不被切换的操作系统调度程序中断的情况下执行线程之间的CPU。你应该使用 mutexes为了在打印时停止其他线程。这里有一个很好的例子:

http://sourcecookbook.com/en/recipes/70/basic-and-easy-pthread-mutex-lock-example-c-thread-synchronization

关于C++ 打印/cout 在多线程中重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25848615/

相关文章:

python - 同时在不同目录 (os.chdir) 中工作(并行线程)

c++ - 在 C++ 中使用非虚拟公共(public)接口(interface)和作用域锁避免死锁

Python用win32print打印pdf文件

wpf - WPF打印-在WPF PrintDialog上自动设置打印机

c++ - 为什么 operator<< 的重载必须通过引用返回?

c++ - 如果数组是通过引用传递的,为什么我们应该在函数中定义一个新的指针?

c++ - 如何将字符串转换为具有确定宽度的整数数组

C++简单凯撒密码算法

python - 停止两个循环线程连续接收和发送数据

printing - 如何使用GeoServer-GeoWebCache层的MapFish打印模块?