I'd like to write a function for logging which should be used like this:
log(__FILE__) << "My message containing integer: " << 123 << " and double: " << 1.2;
This should print the following line, add endl and flush immediately:
main.cpp: My message containing integer: 123 and double: 1.2
My (simplified) attempt for the implementation of the function:
class Writer
{
public:
template<typename T>
Writer & operator<<(T t)
{
cout << t << endl;
cout.flush();
return (*this);
}
};
Writer log(const char* fileName)
{
cout << fileName << ": ";
return Writer();
}
int main(int argc, const char *argv[])
{
log(__FILE__) << "My message containing integer: " << 123 << "and double: " << 1.2;
return 0;
}
My problem is that because of L-R associativity of the operator<< the output is:
main.cpp: My message containing integer:
123
and double:
1.2
Is there any way how to implement the function or is my requirement for its usage unrealizable?
Ideally I'd like to use plain C++03 (i.e. no C++11 features, boost and non-standard libraries).
L-R associativity is not related to your problem (if you talk about line breaks). The problem is because you use endl after each write. You don't need it (and if you do that, then you don't need flush, because endl already flushes the output).
The easy solution to your problem:
class Writer
{
public:
template<typename T>
Writer & operator<<(T t)
{
cout << t;
return (*this);
}
~Writer()
{
try {
cout << endl;
}
catch (...) {
// You have to make sure that no
// exception leaves destructor
}
}
};
It is also worth to notice, that your approach is not really scalable: it is impossible to use your code in multi-threaded environment. Assume that two threads are writing into your logging:
Thread 1: log(__FILE__) << "a" << "b" << "c";
Thread 2: log(__FILE__) << "a" << "b" << "c";
Here you can easily get a message "aabbcc\n\n" in your logfile, which is highly undesirable.
In order to avoid that, you can have a static mutex object inside log() function, which you pass into Writer constructor. Then you have to lock it in the constructor and unlock it in the destructor. It will guarantee the synchronization of concurrent writing of different entries.
Related
I have some C++ console programs that display progress information on the last line of output, at regular intervals.
This progress line is cleared prior to writing the next real output (or updated progress information); this could be from a number of different places in the source, and I'm currently clearing the progress line on each one, e.g.:
cout << clearline << "Some real output" << endl;
...
cout << clearline << "Some other real output" << endl;
...
cout << clearline << setw(4) << ++icount << ") " << ... << endl;
...
cout << clearline << "Progress info number " << ++iprog << flush;
Here, 'clearline' is some (system dependent) string like "\r\33[2K" which clears the current last line.
I would prefer something cleaner, that localises source changes to the actual line that's going to be cleared, like simply:
cout << "Progress info number " << ++iprog << flush << defer_clearline;
where 'defer_clearline' causes the writing of 'clearline' to be deferred until just prior to the next cout output, wherever and whatever that happens to be. I then wouldn't need to use 'clearline' on all the other lines.
I thought it might be possible to do this if 'defer_clearline' is a manipulator, and/or using xalloc() and iword().
But I've not managed to get anything that works.
Is it possible to do this sort of thing, and if so how?
2020-12-30: edited to include missing 'flush's.
You can pretty easily setup an std::cout wrapper:
// Declare the empty struct clear_line and instantiate the object cls
struct clear_line { } cls;
class out {
private:
std::ostream &strm = std::cout;
bool is_next_clear = false;
public:
template <typename T>
out& operator<<(const T& obj) {
if(is_next_clear) {
strm << std::endl << std::endl << std::endl; // clear logic
is_next_clear = false;
}
strm << obj;
return *this;
}
out& operator<<(const clear_line& _) {
is_next_clear = true;
return *this;
}
};
This pretty simply stores an is_next_clear bool for whether or not the next regular output should be cleared. Then, in the general case (the templated operator<<()), we run your clear logic and flip the is_next_clear flag if applicable. Then just output as usual.
Then, the operator<<() is overloaded for the case of a clear_line object. So if one of those is sent, we know to flip the is_next_clear flag, but not actually output anything.
Here's an example use:
int main() {
out o;
o << "Some real output" << cls;
o << "Some other real output";
return 0;
}
Here it is in action: https://ideone.com/0Dzwlv
If you want to use endl, you'll need to add a special overload for it as this answer suggests: https://stackoverflow.com/a/1134467/2602718
// this is the type of std::cout
typedef std::basic_ostream<char, std::char_traits<char> > CoutType;
// this is the function signature of std::endl
typedef CoutType& (*StandardEndLine)(CoutType&);
// define an operator<< to take in std::endl
out& operator<<(StandardEndLine manip)
{
// call the function, but we cannot return its value
manip(strm);
return *this;
}
Live example: https://ideone.com/ACUMOo
I have output in a C++ program that I only want to see if a "verbose" option is specified at runtime. I've found lots of methods to use preprocessor #define statements to control debugging output when compiling, but I can't find any ways to do this at runtime short of wrapping every cout in if(verbose).
In pseudocode, I'd like to transform:
if(verbose)
cout << "Some text: " << variable << endl;
...
if(verbose)
cout << "Other text: " << var << endl;
Into:
if(verbose)
//block cout
cout << "Some text: " << variable << endl;
cout << "Other text: " << var << endl;
Is there some way to optionally redefine cout at runtime so those lines silently print nothing? Better yet would be a more flexible approach that allows some output while blocking others.
You can simply bind a stream object reference to different streams depending on verbose:
ostream& vout = (verbose? cout : nullstream);
Then use vout for all the output that should only appear when verbose.
Of course you need to define nullstream first; that involves defining a streambuf derived class.
I'm not sure whether you're in the process of writing a program, or whether you already have a program you want to disable output for. Generally, when you're writing software with debugging output, you'll want to create some sort of logging class to help you control when output occurs and where it goes (e.g., to a file, to stdout, to stderr, etc.). An example of a simple one would be:
#include <iostream>
class Logger {
public:
Logger(bool enabled) : enabled(enabled) { }
void setEnabled(bool enabled) { this->enabled = enabled; }
template<typename T> Logger& operator<<(T const& t)
{
if (enabled)
std::cout << t;
return *this;
}
// If you'd like manipulator support (e.g., for std::endl)
Logger& operator<<(std::ostream& (*manipulator)(std::ostream&))
{
if (enabled)
std::cout << manipulator;
return *this;
}
private:
bool enabled;
};
int main()
{
Logger log(true);
log << "Hello, " << "World!" << 123; // Prints Hello, World!123
log.setEnabled(false);
log << "Hello, " << "World!" << 123; // Prints nothing
}
Alternatively, you could redirect cout, as others have mentioned, or even just simply redirect your program's output to /dev/null on the command line:
./myProgram > /dev/null
I have OpenMP threads that write to the console via cout and cerr. This of course is not safe, since output can be interleaved. I could do something like
#pragma omp critical(cerr)
{
cerr << "my variable: " << variable << endl;
}
It would be nicer if could replace cerr with a thread-safe version, similar to the approach explained in the valgrind DRD manual (http://valgrind.org/docs/manual/drd-manual.html#drd-manual.effective-use) which involves deriving a class from std::ostreambuf. Ideally in the end I would just replace cerr with my own threaded cerr, e.g. simply:
tcerr << "my variable: " << variable << endl;
Such a class could print to the console as soon as it encounters an "endl". I do not mind if lines from different threads are interleaved, but each line should come only from one thread.
I do not really understand how all this streaming in C++ works, it is too complicated. Has anybody such a class or can show me how to create such a class for that purpose?
As others pointed out, in C++11, std::cout is thread-safe.
However if you use it like
std::cout << 1 << 2 << 3;
with different threads, the output can still be interleaved, since every << is a new function call which can be preceeded by any function call on another thread.
To avoid interleaving without a #pragma omp critical - which would lock everything - you can do the following:
std::stringstream stream; // #include <sstream> for this
stream << 1 << 2 << 3;
std::cout << stream.str();
The three calls writing 123 to the stream are happening in only one thread to a local, non-shared object, therefore aren't affected by any other threads. Then, there is only one call to the shared output stream std::cout, where the order of items 123 is already fixed, therefore won't get messed up.
You can use an approach similar to a string builder. Create a non-template class that:
offers templated operator<< for insertion into this object
internally builds into a std::ostringstream
dumps the contents on destruction
Rough approach:
class AtomicWriter {
std::ostringstream st;
public:
template <typename T>
AtomicWriter& operator<<(T const& t) {
st << t;
return *this;
}
~AtomicWriter() {
std::string s = st.str();
std::cerr << s;
//fprintf(stderr,"%s", s.c_str());
// write(2,s.c_str(),s.size());
}
};
Use as:
AtomicWriter() << "my variable: " << variable << "\n";
Or in more complex scenarios:
{
AtomicWriter w;
w << "my variables:";
for (auto & v : vars) {
w << ' ' << v;
}
} // now it dumps
You will need to add more overloads if you want manipulators, you can use write better than fprintf for the atomic write in the destructor, or std::cerr, you can generalize so that the destination is passed to the constructor (std::ostream/file descriptor/FILE*),
I don't have enough reputation to post a comment, but I wanted to post my addition to the AtomicWriter class to support std::endl and allow for other streams to be used besides std::cout. Here it is:
class AtomicWriter {
std::ostringstream st;
std::ostream &stream;
public:
AtomicWriter(std::ostream &s=std::cout):stream(s) { }
template <typename T>
AtomicWriter& operator<<(T const& t) {
st << t;
return *this;
}
AtomicWriter& operator<<( std::ostream&(*f)(std::ostream&) ) {
st << f;
return *this;
}
~AtomicWriter() { stream << st.str(); }
};
Put the following code in header file atomic_stream_macro.h
#ifndef atomic_stream_macro_h
#define atomic_stream_macro_h
#include <mutex>
/************************************************************************/
/************************************************************************/
extern std::mutex print_mutex;
#define PRINT_MSG(out,msg) \
{ \
std::unique_lock<std::mutex> lock (print_mutex); \
\
out << __FILE__ << "(" << __LINE__ << ")" << ": " \
<< msg << std::endl; \
}
/************************************************************************/
/************************************************************************/
#endif
Now the macro can be used from a file as follows.
#include <atomic_stream_macro.h>
#include <iostream>
int foo (void)
{
PRINT_MSG (std::cout, "Some " << "Text " << "Here ");
}
Finally, in the main.cxx, declare the mutex.
#include <mutex>
std::mutex print_mutex;
int main (void)
{
// launch threads from here
}
You could do it by inheriting std::basic_streambuf, and override the correct functions to make it threadsafe. Then use this class for your stream objects.
I have a multi-threaded application, which heavily uses std::cout for logging without any locking. In such a case, how can I easily add lock mechanism to make std::cout thread-safe?
I don't want to search for each occurrence of std::cout and add a line of locking code. That is too tedious.
Any better practice?
While I can't be sure this applies to every compiler / version of std libs
but in the code-base I'm using std::cout::operator<<() it is already thread-safe.
I'm assuming that what you're really trying to do it stop std::cout from mixing string when concatenating with the operator<< multiple time per string, across multiple threads.
The reason strings get garbled is because there is a "External" race on the operator<<
this can lead to things like this happening.
//Thread 1
std::cout << "the quick brown fox " << "jumped over the lazy dog " << std::endl;
//Thread 2
std::cout << "my mother washes" << " seashells by the sea shore" << std::endl;
//Could just as easily print like this or any other crazy order.
my mother washes the quick brown fox seashells by the sea shore \n
jumped over the lazy dog \n
If that's the case there is a much simpler answer than making your own thread safe cout or implementing a lock to use with cout.
Simply compose your string before you pass it to cout
For example.
//There are other ways, but stringstream uses << just like cout..
std::stringstream msg;
msg << "Error:" << Err_num << ", " << ErrorString( Err_num ) << "\n";
std::cout << msg.str();
This way your stings can't be garbled because they are already fully formed, plus its also a better practice to fully form your strings anyway before dispatching them.
Since C++20, you can use std::osyncstream wrapper:
http://en.cppreference.com/w/cpp/io/basic_osyncstream
{
std::osyncstream bout(std::cout); // synchronized wrapper for std::cout
bout << "Hello, ";
bout << "World!";
bout << std::endl; // flush is noted, but not yet performed
bout << "and more!\n";
} // characters are transferred and std::cout is flushed
It provides the guarantee that all output made to the same final
destination buffer (std::cout in the examples above) will be free of
data races and will not be interleaved or garbled in any way, as long
as every write to the that final destination buffer is made through
(possibly different) instances of std::basic_osyncstream.
Alternatively, you can use a temporary:
std::osyncstream(std::cout) << "Hello, " << "World!" << '\n';
Note: This answer is pre-C++20 so it does not use std::osyncstream with its separate buffering, but uses a lock instead.
I guess you could implement your own class which wraps cout and associates a mutex with it. The operator << of that new class would do three things:
create a lock for the mutex, possibly blocking other threads
do the output, i.e. do the operator << for the wrapped stream and the passed argument
construct an instance of a different class, passing the lock to that
This different class would keep the lock and delegate operator << to the wrapped stream. The destructor of that second class would eventually destroy the lock and release the mutex.
So any output you write as a single statement, i.e. as a single sequence of << invocations, will be printed atomically as long as all your output goes through that object with the same mutex.
Let's call the two classes synchronized_ostream and locked_ostream. If sync_cout is an instance of synchronized_ostream which wraps std::cout, then the sequence
sync_cout << "Hello, " << name << "!" << std::endl;
would result in the following actions:
synchronized_ostream::operator<< would aquire the lock
synchronized_ostream::operator<< would delegate the printing of "Hello, " to cout
operator<<(std::ostream&, const char*) would print "Hello, "
synchronized_ostream::operator<< would construct a locked_ostream and pass the lock to that
locked_ostream::operator<< would delegate the printing of name to cout
operator<<(std::ostream&, std::string) would print the name
The same delegation to cout happens for the exclamation point and the endline manipulator
The locked_ostream temporary gets destructed, the lock is released
I really like the trick from Nicolás given in this question of creating a temporary object and putting the protection code on the destructor.
/** Thread safe cout class
* Exemple of use:
* PrintThread{} << "Hello world!" << std::endl;
*/
class PrintThread: public std::ostringstream
{
public:
PrintThread() = default;
~PrintThread()
{
std::lock_guard<std::mutex> guard(_mutexPrint);
std::cout << this->str();
}
private:
static std::mutex _mutexPrint;
};
std::mutex PrintThread::_mutexPrint{};
You can then use it as a regular std::cout, from any thread:
PrintThread{} << "my_val=" << val << std::endl;
The object collect data as a regular ostringstream. As soon the coma is reached, the object is destroyed and flush all collected information.
Along the lines of the answer suggested by Conchylicultor, but without inheriting from std::ostringstream:
EDIT: Fixed return type for the overloaded operator and added overload for std::endl.
EDIT 1: I have extended this into a simple header-only library for logging / debugging multi-threaded programs.
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <chrono>
static std::mutex mtx_cout;
// Asynchronous output
struct acout
{
std::unique_lock<std::mutex> lk;
acout()
:
lk(std::unique_lock<std::mutex>(mtx_cout))
{
}
template<typename T>
acout& operator<<(const T& _t)
{
std::cout << _t;
return *this;
}
acout& operator<<(std::ostream& (*fp)(std::ostream&))
{
std::cout << fp;
return *this;
}
};
int main(void)
{
std::vector<std::thread> workers_cout;
std::vector<std::thread> workers_acout;
size_t worker(0);
size_t threads(5);
std::cout << "With std::cout:" << std::endl;
for (size_t i = 0; i < threads; ++i)
{
workers_cout.emplace_back([&]
{
std::cout << "\tThis is worker " << ++worker << " in thread "
<< std::this_thread::get_id() << std::endl;
});
}
for (auto& w : workers_cout)
{
w.join();
}
worker = 0;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "\nWith acout():" << std::endl;
for (size_t i = 0; i < threads; ++i)
{
workers_acout.emplace_back([&]
{
acout() << "\tThis is worker " << ++worker << " in thread "
<< std::this_thread::get_id() << std::endl;
});
}
for (auto& w : workers_acout)
{
w.join();
}
return 0;
}
Output:
With std::cout:
This is worker 1 in thread 139911511856896
This is worker This is worker 3 in thread 139911495071488
This is worker 4 in thread 139911486678784
2 in thread This is worker 5 in thread 139911503464192139911478286080
With acout():
This is worker 1 in thread 139911478286080
This is worker 2 in thread 139911486678784
This is worker 3 in thread 139911495071488
This is worker 4 in thread 139911503464192
This is worker 5 in thread 139911511856896
For fast debugging c++11 applications and avoid interleaved output I just write small functions like these:
...
#include <mutex>
...
mutex m_screen;
...
void msg(char const * const message);
...
void msg(char const * const message)
{
m_screen.lock();
cout << message << endl;
m_screen.unlock();
}
I use these types of functions for outputs and if numeric values are needed I just use something like this:
void msgInt(char const * const message, int const &value);
...
void msgInt(char const * const message, int const &value)
{
m_screen.lock();
cout << message << " = " << value << endl;
m_screen.unlock();
}
This is easy and works fine to me, but I don't really know if it is technically correct. So I would be glad to hear your opinions.
Well, I didn't read this:
I don't want to search for each occurrence of std::cout and add a line of locking code.
I'm sorry. However I hope it helps somebody.
A feasible solution uses a line-buffer for each thread. You might get interleaved lines, but not interleaved characters. If you attach that to thread-local storage, you also avoid lock contention issues. Then, when a line is full (or on flush, if you want), you write it to stdout. This last operation of course has to use a lock. You stuff all this into a streambuffer, which you put between std::cout and its original streambuffer (a.k.a. Decorator Pattern).
The problem this doesn't solve is things like format flags (e.g. hex/dec/oct for numbers), which can sometimes percolate between threads, because they are attached to the stream. It's nothing bad, assuming you're only logging and not using it for important data. It helps to just not format things specially. If you need hex output for certain numbers, try this:
template<typename integer_type>
std::string hex(integer_type v)
{
/* Notes:
1. using showbase would still not show the 0x for a zero
2. using (v + 0) converts an unsigned char to a type
that is recognized as integer instead of as character */
std::stringstream s;
s << "0x" << std::setfill('0') << std::hex
<< std::setw(2 * sizeof v) << (v + 0);
return s.str();
}
Similar approaches work for other formats as well.
I know its an old question, but it helped me a lot with my problem. I created an utility class based on this post answers and I'd like to share my result.
Considering we use C++11 or latter C++ versions, this class provides print and println functions to compose strings before calling the standard output stream and avoid concurrency problems. These are variadic functions which use templates to print different data types.
You can check its use in a producer-consumer problem on my github: https://github.com/eloiluiz/threadsBar
So, here is my code:
class Console {
private:
Console() = default;
inline static void innerPrint(std::ostream &stream) {}
template<typename Head, typename... Tail>
inline static void innerPrint(std::ostream &stream, Head const head, Tail const ...tail) {
stream << head;
innerPrint(stream, tail...);
}
public:
template<typename Head, typename... Tail>
inline static void print(Head const head, Tail const ...tail) {
// Create a stream buffer
std::stringbuf buffer;
std::ostream stream(&buffer);
// Feed input parameters to the stream object
innerPrint(stream, head, tail...);
// Print into console and flush
std::cout << buffer.str();
}
template<typename Head, typename... Tail>
inline static void println(Head const head, Tail const ...tail) {
print(head, tail..., "\n");
}
};
This is how I manage thread safe operations on std::cout using a custom enum and macros:
enum SynchronisedOutput { IO_Lock, IO_Unlock };
inline std::ostream & operator<<(std::ostream & os, SynchronisedOutput so) {
static std::mutex mutex;
if (IO_Lock == so) mutex.lock();
else if (IO_Unlock == so)
mutex.unlock();
return os;
}
#define sync_os(Os) (Os) << IO_Lock
#define sync_cout sync_os(std::cout)
#define sync_endl '\n' << IO_Unlock
This allow me to write things like:
sync_cout << "Hello, " << name << '!' << sync_endl;
in threads without racing issues.
I had a similar problem to yours. You can use the following class.
This only supports outputting to std::cout, but if you need a general one let me know. In the code below, tsprint creates an inline temporary object of the class ThreadSafePrinter. If you want, you can change tsprint to cout if you have used cout instead of std::cout, so you won't have to replace any instances of cout but I do not recommend such a practice in general. It is much better to use a special output symbol for such debug lines starting from the beginning of the project anyway.
I like this solution as well: 1.
In my solution all threads can continue inserting into their corresponding thread_local stringstream static-objects and then lock the mutex only when it is required to flush which is triggered in the destructor. This is expected to improve the efficiency by shortening the duration during which the mutex-lock is held. Maybe I can include a mechanism similar to the sync_endl solution mentioned in 1.
class ThreadSafePrinter
{
static mutex m;
static thread_local stringstream ss;
public:
ThreadSafePrinter() = default;
~ThreadSafePrinter()
{
lock_guard lg(m);
std::cout << ss.str();
ss.clear();
}
template<typename T>
ThreadSafePrinter& operator << (const T& c)
{
ss << c;
return *this;
}
// this is the type of std::cout
typedef std::basic_ostream<char, std::char_traits<char> > CoutType;
// this is the function signature of std::endl
typedef CoutType& (*StandardEndLine)(CoutType&);
// define an operator<< to take in std::endl
ThreadSafePrinter& operator<<(StandardEndLine manip)
{
manip(ss);
return *this;
}
};
mutex ThreadSafePrinter::m;
thread_local stringstream ThreadSafePrinter::ss;
#define tsprint ThreadSafePrinter()
void main()
{
tsprint << "asd ";
tsprint << "dfg";
}
In addition to synchronisation this solution provides information about the thread from which the log was written.
DISCLAIMER: It's quite a naive way of syncing the logs, however it might be applicable for some small use cases for debugging.
thread_local int thread_id = -1;
std::atomic<int> thread_count;
struct CurrentThread {
static void init() {
if (thread_id == -1) {
thread_id = thread_count++;
}
}
friend std::ostream &operator<<(std::ostream &os, const CurrentThread &t) {
os << "[Thread-" << thread_id << "] - ";
return os;
}
};
CurrentThread current_thread;
std::mutex io_lock;
#ifdef DEBUG
#define LOG(x) {CurrentThread::init(); std::unique_lock<std::mutex> lk(io_lock); cout << current_thread << x << endl;}
#else
#define LOG(x)
#endif
This can be used like this.
LOG(cout << "Waiting for some event");
And it will give log output
[Thread-1] - Entering critical section
[Thread-2] - Waiting on mutex
[Thread-1] - Leaving critical section, unlocking the mutex
So I have such log class:
#include <iostream>
#include <sstream>
#include <boost/circular_buffer.hpp>
#include <boost/foreach.hpp>
class FlushInternal;
class Log
{
public:
static FlushInternal* endl;
Log(int log_length)
{
i = 0;
messages_buffer = new boost::circular_buffer<std::string>(log_length);
}
template <class T>
Log &operator<<(const T &v)
{
current_message << v;
return *this;
}
Log &operator<<(std::ostream&(*f)(std::ostream&))
{
current_message << *f;
return *this;
}
Log &operator<<(FlushInternal*)
{
++i;
messages_buffer->push_back(current_message.str());
clean_stringstream(current_message);
is_filled();
return *this;
}
boost::circular_buffer<std::string> *messages_buffer;
private:
int i;
std::stringstream current_message;
void is_filled()
{
if (i >= messages_buffer->capacity())
{
i = 0;
BOOST_FOREACH(std::string s, *messages_buffer)
{
std::cout << ++i << ": " << s << " ;" << std::endl;
}
i = 0;
}
}
void clean_stringstream(std::stringstream &message)
{
message.flush();
message.clear();
message.seekp(0);
message.str("");
}
};
FlushInternal* Log::endl = 0;
And I can Use it like this:
#include <log.h>
int main()
{
Log l(2);
l << "message one: " << 1 << Log::endl;
l << "message two:" << " " << 2 << Log::endl;
l << "message " << "three: " << 3 << Log::endl;
l << "message" << " " << "four: " << 4 << Log::endl;
std::cin.get();
}
This would output:
1: message one: 1 ;
2: message two: 2 ;
1: message three: 3 ;
2: message four: 4 ;
As you can see I can have as many << as I want inside each log message. I want to be capable to use one instance of Log class from many threads at the same time. So I would have something like (pseudocode that compiles, runs but traces nothing.):
#include <boost/thread.hpp>
#include <log.h>
Log *l;
void fun_one()
{
*l << "message one: " << 1 << Log::endl;
*l << "message two:" << " " << 2 << Log::endl;
}
void fun_two()
{
*l << "message " << "three: " << 3 << Log::endl;
*l << "message" << " " << "four: " << 4 << Log::endl;
}
int main()
{
l = new Log(2);
boost::thread(fun_one);
boost::thread(fun_two);
std::cin.get();
}
So as you can see I want messages to be inserted into log in multythreaded function. Lo I wonder - how to make my log cclass support this?
The approach linked by trojanfoe is pretty much the canonical one. Basically create some temporary thing for the leftmost << operator, accumulate everything, and output the message in the destructor for the temporary thing.
The only question is the exact mechanics of this accumulator. The example used ostringstream, but I've seen the ofstream for the log file used directly as well (requires locking to ensure the output ends up on one line).
Creating ostringstreams is relatively expensive on some platforms, because they may need to lock and copy some internal locale related things. You could re-implement also the << operator for interesting types, but I'd test the ostringstream approach first.
A useful optimization is determine at the point of the construction of the temporary whether the trace will be emitted (e.g., whether tracing is enabled at that particular level), and not create the guts of the temporary at all in that case - all the insertion operations will be no-ops.
Here's one approach:
http://drdobbs.com/cpp/201804215
It basically creates a new ostringstream object each time you perform logging, which makes it thread safe. I can't say I'm that keen on that, as it seems a little clumsy to me.
You might have a look at the Qt logging classes as they support the << operator, however I'm not sure about thread safety.