#include "WorkerThread.h"
#include "Logger.h"
#include <sstream>

namespace comm {

WorkerThread::WorkerThread()
    : tasks(folly::MPMCQueue<std::unique_ptr<taskType>>(20)) {
  auto job = [this]() {
    while (true) {
      std::unique_ptr<taskType> lastTask;
      this->tasks.blockingRead(lastTask);
      if (lastTask == nullptr) {
        break;
      }
      (*lastTask)();
    }
  };
  this->thread = std::make_unique<std::thread>(job);
}

void WorkerThread::scheduleTask(const taskType task) {
  if (!this->tasks.write(std::make_unique<taskType>(std::move(task)))) {
    throw std::runtime_error("Error scheduling task on Database thread");
  }
}

WorkerThread::~WorkerThread() {
  this->tasks.blockingWrite(nullptr);
  try {
    this->thread->join();
  } catch (const std::system_error &error) {
    std::ostringstream stringStream;
    stringStream << "Error occurred joining the Database thread: "
                 << error.what();
    Logger::log(stringStream.str());
  }
}

} // namespace comm

#include "WorkerThread.h"
#include "Logger.h"
#include <sstream>

namespace comm {

WorkerThread::WorkerThread()
    : tasks(folly::MPMCQueue<std::unique_ptr<taskType>>(20)) {
  auto job = [this]() {
    while (true) {
      std::unique_ptr<taskType> lastTask;
      this->tasks.blockingRead(lastTask);
      if (lastTask == nullptr) {
        break;
      }
      (*lastTask)();
    }
  };
  this->thread = std::make_unique<std::thread>(job);
}

void WorkerThread::scheduleTask(const taskType task) {
  if (!this->tasks.write(std::make_unique<taskType>(std::move(task)))) {
    throw std::runtime_error("Error scheduling task on a worker thread");
  }
}

WorkerThread::~WorkerThread() {
  this->tasks.blockingWrite(nullptr);
  try {
    this->thread->join();
  } catch (const std::system_error &error) {
    std::ostringstream stringStream;
    stringStream << "Error occurred joining a worker thread: " << error.what();
    Logger::log(stringStream.str());
  }
}

} // namespace comm

Refactor error messages for worker threads
[native] Refactor error messages for worker threads

Summary:
Doing D1410 I missed the error messages that still indicate the operations are done on the database thread, while the rest of the code became more generic. To keep it consistent I think we should change those messages accordingly.
I was also thinking, maybe we should allow the developer to name worker threads? So we could then require a string name in the constructor of the worker thread and those error messages would contain that name so the developer would be informed clearly on which thread there was an error.
What do you think?

Test Plan: Honestly, none.

Reviewers: palys-swm, ashoat

Reviewed By: palys-swm, ashoat

Subscribers: ashoat, KatPo, palys-swm, Adrian, atul

Differential Revision: https://phabricator.ashoat.com/D1421
