我使用std :: cout打印控制台上的日志。由于程序是多线程的,如果我在cout之后使用多个“<<”操作,则打印结果将是无序的。
例如,如果一个线程执行cout<< "A" << "B" << endl;
,则另一个线程可能在A和B之间执行cout << "C";
。结果将是“ACB”。
因此,我将编写一个新类来继承ostream
(实际上是basic_ostream<char, char_traits<char>>
)并在cout初始化时添加一个锁,因此打印输出应遵循正确的顺序。
一种选择是创建一个包含对流的引用的类,但在整个生命周期中保持锁定。这是一个简单的例子:
#include <iostream>
#include <mutex>
struct LockedOstream {
std::lock_guard<std::mutex> lg_;
std::ostream& os_;
LockedOstream(std::mutex& m, std::ostream& os)
: lg_{m}
, os_{os}
{ }
std::ostream& stream() const { return os_; }
};
int main()
{
std::mutex m;
LockedOstream(m, std::cout).stream() << "foo " << "bar\n";
// ^ locked now ^ unlocked now
}
只要构成输出的单个“单位”的所有打印都出现在同一语句中,这就可以工作。
编辑:实际上,继承版本比我原先预期的好很多:
#include <iostream>
#include <mutex>
class LockedOstream : public std::ostream {
static std::mutex& getCoutMutex()
// use a Meyers' singleton for the cout mutex to keep this header-only
{
static std::mutex m;
return m;
}
std::lock_guard<std::mutex> lg_;
public:
// Generic constructor
// You need to pass the right mutex to match the stream you want
LockedOstream(std::mutex& m, std::ostream& os)
: std::ostream(os.rdbuf())
, lg_{m}
{ }
// Cout specific constructor
// Uses a mutex singleton specific for cout
LockedOstream()
: LockedOstream(getCoutMutex(), std::cout)
{ }
};
int main()
{
LockedOstream() << "foo " << "bar\n";
// ^ locked now ^ unlocked now
}
作为旁白:
(虽然后者有时会引起争议,但至少知道并做出明智的选择是个好主意)。
您可以定义自己的功能
template<typename... Ts>
void locked_print(std::ostream& stream, Ts&&... ts)
{
static std::mutex mtx;
std::lock_guard<std::mutex> guard(mtx);
(stream << ... << std::forward<Ts>(ts));
}
当你想确定它是独家的时,你可以称之为locked_print(std::cout, 1, 2, "bar");
由于outstream << x1 << x2 << ...
是多个函数调用,除了锁定所有内容直到破坏同一个外流之外,你无法在内部执行此操作。您可以在调用时强制约束:
{
std::lock_guard<std::mutex> guard(global_mutex);
// your print here
}