c++ - Threading In Classes -


i creating asynchronous class logs strings file. should creating thread within class itself? thinking start function

void async_log::start (void) {   std::thread thread_log(     [&]()     {       std::ofstream fout;       fout.open(filename);       while(true)       {         if(q.size())         {           std::lock_guard<std::mutex> lock(m);           fout << q.front() <<  "\t @ time: " << std::clock() << std::endl;           q.pop();         }       }       fout.close();     }); } 

or better leave threading main. first concern if threading unique (so if instantiate class 2 times 2 different files thread_log on written or have conflict).

there nothing wrong have dedicated thread in class, want note several things:

  1. inside thread implement busy waiting log messages. redundant , expensive! thread consumes cpu when there no messages in queue. need blocking queue there, block on pop() method. can find implementation of blocking queue c++ here or here.

  2. there need provide possibilty terminate logging thread. can eigher having 'terminate' variable check in loop, or sending special 'poison pill' message logger.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -