【问题标题】:Concurrent cout formatting并发 cout 格式化
【发布时间】:2017-09-29 08:19:56
【问题描述】:

这是一个学术问题。

sdt::mutex m;
typedef std::lock_guard<std::mutex> G;

void thread1(){
  G g(m);       
  std::cout << std::setw(9);
  std::cout << 3.14;
  std::cout << std::endl;
}

void thread2(){
  G g(m);       
  std::cout << std::setw(7);
  std::cout << 3.14;
  std::cout << std::endl;
}

我的问题是格式绑定到输出流,所以如果我想确定我产生的输出,我需要设置我的线程上发明的所有格式选项。明年哪个会起作用,或者不会起作用。

  • 有什么方法可以在不手动设置所有内容的情况下将格式重置为默认值?
  • 如果不是,有什么好的解决方法?
    • 例如,我是否应该在我的线程本地创建并保留一个std::ostringstream 并将oss.str() 写入std::cout

【问题讨论】:

标签: c++ multithreading c++14 stdout


【解决方案1】:

为了简洁起见,我使用了 boost,但您可以编写自己的可选和状态保护程序。

#include <mutex>
#include <iostream>
#include <iomanip>
#include <tuple>
#include <utility>
#include <boost/io/ios_state.hpp>
#include <boost/optional.hpp>

std::mutex m;

struct save_and_lock
{
    boost::optional<boost::io::ios_all_saver> saver;
    std::unique_lock<std::mutex> lock;

    void init(std::ostream& os)
    {
        lock = std::unique_lock<std::mutex>(m);
        saver.emplace(os);
        os.flags(std::ios_base::fmtflags(0));
    }

    friend std::ostream& operator<<(std::ostream& os, save_and_lock&& s)
    {
        s.init(os);
        return os;
    }
};

void thread1(){
    std::cout << save_and_lock() << std::setw(9) << 3.14 << std::endl;
}

void thread2(){
    std::cout << save_and_lock() << std::setw(9) << 3.14 << std::endl;

}

这会起作用,因为用户定义的operator &lt;&lt; 的评估顺序是从左到右的。

【讨论】:

  • 哇!我不知道那里可以实现朋友功能。从何时起?谷歌搜索......从那时起!哇!
  • @Notinlist c++ 充满惊喜吧?
猜你喜欢
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
相关资源
最近更新 更多