/*
  This file is part of CDO. CDO is a collection of Operators to manipulate and analyse Climate model Data.

  Author: Uwe Schulzweida

*/

#pragma once

#include <version>
#include <atomic>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <thread>

void workerThread_set_ompNumMaxThreads(int maxThreads);

class WorkerThread
{
private:
  enum struct State
  {
    SETUP,
    IDLE,
    JOB,
    DIE
  };

  std::function<void()> function;
  std::atomic<State> state{ State::SETUP };
#if __cpp_lib_jthread >= 201911L
  std::jthread thread;
#else
  std::thread thread;
#endif
  std::mutex workMutex;
  std::mutex bossMutex;
  std::unique_lock<std::mutex> bossLock;
  std::condition_variable workCond;
  std::condition_variable bossCond;

  static void task(WorkerThread *self);

public:
  WorkerThread();
  ~WorkerThread();

  void doAsync(std::function<void()> func);
  void wait();
};
