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:
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.
there need provide possibilty terminate logging thread. can eigher having 'terminate' variable check in loop, or sending special 'poison pill' message logger.
Comments
Post a Comment