I am having the worst time trying to make a class that has a std::ofstream and a std::mutex that is locked and unlocked to control access to the ofstream.
Basically I want a class thread_safe_ofstreamwith a << operator so I can use it like:
thread_safe_ofstream ofs;
ofs << "debug info from different threads" << std::endl;
So I know I need an operator<< overload. While there is plenty of info for this operator<< for classes on the right-hand-side of <<, I cannot find any documentation for how to implement your own ostream-like << input.
I know the following code cannot work because of whatever input/output requirements << has, but this is the spirit of the class I need.
Class thread_safe_ofstream
{
std::mutex mu;
std::ofstream stream;
template<typename T>
operator<<(T& thing)
{
mu.lock();
stream << thing;
mu.unlock();
}
};
This way a single thread_safe_ofstream can be <<'d to from multiple threads without problems (my hope is).