Diag-Client-Lib
executor.h
Go to the documentation of this file.
1 /* Diagnostic Client library
2  * Copyright (C) 2024 Avijit Dey
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7  */
8 #ifndef DIAGNOSTIC_CLIENT_LIB_LIB_UTILITY_UTILITY_EXECUTOR_H
9 #define DIAGNOSTIC_CLIENT_LIB_LIB_UTILITY_UTILITY_EXECUTOR_H
10 
11 #include <condition_variable>
12 #include <cstdint>
13 #include <functional>
14 #include <mutex>
15 #include <queue>
16 #include <thread>
17 
18 namespace utility {
19 namespace executor {
20 
21 template<typename ExecutorHandler>
22 class Executor {
23  public:
24  // ctor
25  Executor() : exit_request_{false}, running_{false} {
26  thread_ = std::thread([&]() {
27  std::unique_lock<std::mutex> exit_lck(exit_mutex_lock_);
28  while (!exit_request_.load()) {
29  if (!running_.load()) { cond_var_.wait(exit_lck); }
30  if (running_) {
31  std::unique_lock<std::mutex> lck(mutex_lock_);
32  while (!queue_.empty()) {
33  auto func = queue_.front();
34  lck.unlock();
35  func();
36  lck.lock();
37  queue_.pop();
38  }
39  running_.store(false);
40  }
41  }
42  });
43  }
44 
45  // dtor
47  exit_request_ = true;
48  running_ = false;
49  cond_var_.notify_one();
50  thread_.join();
51  }
52 
53  // function to add job to executor
54  void AddExecute(ExecutorHandler executor_handler) {
55  std::unique_lock<std::mutex> lck(mutex_lock_);
56  queue_.push(std::move(executor_handler));
57  running_.store(true);
58  cond_var_.notify_one();
59  }
60 
61  private:
62  // queue to store the elements
63  std::queue<ExecutorHandler> queue_;
64  // mutex to lock the critical section
65  std::mutex mutex_lock_;
66  // mutex to lock the critical section
67  std::mutex exit_mutex_lock_;
68  // threading var
69  std::thread thread_;
70  // conditional variable to block the thread
71  std::condition_variable cond_var_;
72  // flag to terminate the thread
73  std::atomic<bool> exit_request_;
74  // flag th start the thread
75  std::atomic<bool> running_;
76 };
77 } // namespace executor
78 } // namespace utility
79 #endif // DIAGNOSTIC_CLIENT_LIB_LIB_UTILITY_UTILITY_EXECUTOR_H
std::queue< ExecutorHandler > queue_
Definition: executor.h:63
std::atomic< bool > exit_request_
Definition: executor.h:73
void AddExecute(ExecutorHandler executor_handler)
Definition: executor.h:54
std::atomic< bool > running_
Definition: executor.h:75
std::condition_variable cond_var_
Definition: executor.h:71
std::mutex exit_mutex_lock_
Definition: executor.h:67