One option would be to create a class that holds a reference to a stream, but holds a lock throughout it's lifetime. Here's a simple example:
#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
}
This works as long as all the printing that forms a single "unit" of output all occurs in the same statement.
Edit: Actually, the inheritance version is a lot nicer than I originally expected:
#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
}
As an aside:
(though the latter is sometimes contentious, but at least it's a good idea to know and make an informed choice).