1

I am creating an asynchronous class that logs strings into a file. Should I be creating the thread within the class itself? I was thinking something like this as a 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 At Time: " << std::clock() << std::endl;
          q.pop();
        }
      }
      fout.close();
    });
}

Or would it be better to leave the threading up to main. My first concern is if threading is unique (so if I instantiate the class 2 times with two different files will the thread_log be over written or have a conflict).

tshepang
  • 12,111
  • 21
  • 91
  • 136
ChewOnThis_Trident
  • 2,105
  • 2
  • 18
  • 22

1 Answers1

2

There is nothing wrong to have a dedicated thread in the class, but I want to note several things:

  1. Inside your thread you implement busy waiting for log messages. This is completely redundant and very expensive! Your thread consumes CPU even when there are no messages in the queue. What you need is blocking queue there, that would block on pop() method. You can find implementation of the blocking queue for C++ here or here.

  2. There is need to provide possibilty to terminate your logging thread. This you can do eigher by having 'terminate' variable that you check in the loop, or by sending special 'poison pill' message to the logger.

Community
  • 1
  • 1
nogard
  • 9,432
  • 6
  • 33
  • 53