LogIt++
Loading...
Searching...
No Matches
TaskExecutor.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef _LOGIT_TASK_EXECUTOR_HPP_INCLUDED
3#define _LOGIT_TASK_EXECUTOR_HPP_INCLUDED
6
7#include <thread>
8#include <queue>
9#include <mutex>
10#include <functional>
11#include <condition_variable>
12
13namespace logit {
14
21 public:
25 static TaskExecutor instance;
26 return instance;
27 }
28
31 void add_task(std::function<void()> task) {
32 std::unique_lock<std::mutex> lock(m_queue_mutex);
33 m_tasks_queue.push(std::move(task));
34 lock.unlock();
35 m_queue_condition.notify_one();
36 }
37
39 void wait() {
40 for (;;) {
41 std::unique_lock<std::mutex> lock(m_queue_mutex);
42 if (m_tasks_queue.empty()) return;
43 lock.unlock();
44 std::this_thread::yield();
45 std::this_thread::sleep_for(std::chrono::milliseconds(1));
46 }
47 }
48
49 private:
50 std::queue<std::function<void()>> m_tasks_queue;
51 mutable std::mutex m_queue_mutex;
52 std::condition_variable m_queue_condition;
53 std::thread m_worker_thread;
55
58 for (;;) {
59 std::function<void()> task;
60 std::unique_lock<std::mutex> lock(m_queue_mutex);
61 m_queue_condition.wait(lock, [this]() {
62 return !m_tasks_queue.empty() || m_stop_flag;
63 });
64 if (m_stop_flag && m_tasks_queue.empty()) {
65 return;
66 }
67 task = std::move(m_tasks_queue.front());
68 m_tasks_queue.pop();
69 lock.unlock();
70 task();
71 }
72 }
73
77 }
78
81 std::unique_lock<std::mutex> lock(m_queue_mutex);
82 m_stop_flag = true;
83 lock.unlock();
84 m_queue_condition.notify_one();
85 if (m_worker_thread.joinable()) {
86 m_worker_thread.join();
87 }
88 }
89
90 // Delete copy constructor and assignment operators to enforce singleton usage.
91 TaskExecutor(const TaskExecutor&) = delete;
95 };
96
97}; // namespace logit
98
99#endif // _LOGIT_TASK_EXECUTOR_HPP_INCLUDED
A thread-safe task executor that processes tasks in a dedicated worker thread.
void add_task(std::function< void()> task)
Adds a task to the queue in a thread-safe manner.
std::mutex m_queue_mutex
Mutex to protect access to the task queue.
~TaskExecutor()
Destructor that stops the worker thread and cleans up resources.
TaskExecutor(TaskExecutor &&)=delete
bool m_stop_flag
Flag indicating if the worker thread should stop.
TaskExecutor(const TaskExecutor &)=delete
std::queue< std::function< void()> > m_tasks_queue
Queue holding tasks to be executed.
TaskExecutor & operator=(TaskExecutor &&)=delete
void wait()
Waits for all tasks in the queue to be processed.
TaskExecutor & operator=(const TaskExecutor &)=delete
std::thread m_worker_thread
Worker thread for executing tasks.
void worker_function()
The worker thread function that processes tasks from the queue.
static TaskExecutor & get_instance()
Get the singleton instance of the TaskExecutor.
std::condition_variable m_queue_condition
Condition variable to signal task availability.
TaskExecutor()
Private constructor to enforce the singleton pattern.
The primary namespace for the LogIt++ library.