vendredi 27 mars 2015

One instance of class per thread, C++11

I'm writing a logging-utility for a multithreaded application which I'd like to be able to call in a std::cout-like manner:


Thread 1:



Logger::log << "First message" << Logger::end;


Thread 2:



Logger::log << "Second message" << Logger::end;


Once Logger::end is passed to the log that message should be flushed to file/screen/network/whatever the log goes to. In order to handle concurrent writes to the log without mixing up messages my idea is to have one Logger::loginstance for each thread, these instances then share access to a threadsafe queue with a worker thread dedicated to popping new messages and writing them to file/screen etc.


One way to implement that I guess is to have some sort of a multi-singleton returning an instance depending on which thread id is calling it (mapping from thread id to log stored in a std::map perhaps). Is there a better and/or more efficient way?


Are there other designs without the need of one log instance per thread which I have overlooked? How does std::cout handle concurrent access?


Thanks!


Aucun commentaire:

Enregistrer un commentaire