【问题标题】:Guard protection of global stream does not seem to work全局流的保护似乎不起作用
【发布时间】:2017-03-12 03:15:41
【问题描述】:

我不明白为什么下面使用 cout 的代码似乎不起作用。控制台输出似乎每隔一段时间就会出现乱码。如果我使用 Qt 库(本地到 shared_print 函数)制作本地控制台流,代码可以正常工作。我不知道如何制作本地块范围的 cout,这就是为什么我在示例中使用 Qt 控制台流作为概念证明。

有趣的是,cout 示例不起作用,因为我认为我对 cout 的谨慎使用应该避免此特定代码中的竞争条件。我意识到,如果某些东西是全局的,则必须保护对该全局的任何和所有使用......所以人们会认为在这个例子中,它的所有使用都受到保护会起作用,但可惜没有......

#include <QCoreApplication>
#include <iostream>
#include <QTextStream>
#include <thread>                       //C++11 Threading
#include <mutex>                        //Using to get sane console output by avoiding race condition
#include <chrono>                       //Using for timer
#include <sstream>                      //Used to convert thread::id to string

using namespace std;

void shared_print(string s, thread::id id = thread::id(777))
{
    mutex m;
    lock_guard<mutex> guard(m);
    //QTextStream out(stdout);          //WORKS but std::cout doesn't
    stringstream ss;

    ss << id;

    // WORKS
    //if(id != thread::id(777))
    //  out <<  QString::fromStdString(s) << QString::fromStdString(ss.str()) << endl;
    //else
    //  out << QString::fromStdString(s) << endl;

    //DOES NOT WROK
    if(id != thread::id(777))
        cout <<  s << ss.str() << endl;
    else
       cout << s << endl;
}

void func1(int x){
    for(int i = 0; i < 20; i++){
         shared_print("FromThread:" + to_string(x) + " Function:func1" + " ID:" , std::this_thread::get_id() );
    }

}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);


    vector<thread> workers;
    unsigned int numWorkers = std::thread::hardware_concurrency();
    for (unsigned int i = 1; i <= numWorkers; i++) {
        workers.push_back( thread(func1, i) );
    }

//    shared_print("FromMainThread pre join() :: No. of threads C++ recomends: " +  to_string(std::thread::hardware_concurrency()) );
//    shared_print("FromMainThread pre join() :: ID of main Thread   = " , std::this_thread::get_id() );


    for (auto& worker : workers) {          
        if(worker.joinable())               
            worker.join();
    }

    shared_print("main thread post join()");     


    return a.exec();
}

【问题讨论】:

  • 你可能会喜欢我的lock_ios 库。
  • 谢谢 Potatoswatter

标签: c++11


【解决方案1】:

您的互斥锁未按您的需要运行。

    mutex m;
    lock_guard<mutex> guard(m);

这会在每次调用 shared_print 时创建一个不同的互斥体。互斥锁需要存在于函数之外,以便每个线程锁定它,而不是像现在这样每次都创建一个新的。

【讨论】:

  • (或声明static mutex m;。)
  • 谢谢,有道理。
猜你喜欢
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 2023-03-07
  • 2016-05-30
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
相关资源
最近更新 更多