Raftel Engine
 
Loading...
Searching...
No Matches
job_system.hpp
Go to the documentation of this file.
1
30
31#ifndef __JOB_SYSTEM_H__
32#define __JOB_SYSTEM_H__ 1
33
34#pragma once
35
36#include <optional>
37#include <vector>
38#include <thread>
39#include <mutex>
40#include <functional>
41#include <queue>
42#include <future>
43#include <memory>
44#include <raftel/global_macros.hpp>
45
46namespace Raftel {
52 {
53 public:
58
63 static std::unique_ptr<JobSystem> make();
64
71
72 NO_COPYABLE_OR_MOVABLE(JobSystem)
73
74
82 template<typename MyJobFunction, typename... Arguments>
83 auto AddWork(MyJobFunction&& function, Arguments&&... params) -> std::future<decltype(function(params...))>;
84
89
90 private:
91 std::vector<std::thread> workers_;
92 std::mutex queue_mutex_;
93 std::condition_variable warner_job_avaliable_;
94 std::queue<std::function<void()>> work_queue_;
95 bool bStopThreads_;
96 };
97
106 template<typename MyJobFunction, typename ...Arguments>
107 inline auto JobSystem::AddWork(MyJobFunction&& function, Arguments && ...params) -> std::future<decltype(function(params...))>
108 {
109 auto packet = [function = std::move(function), ...params = std::move(params)](){ return function(params...); };
110 std::lock_guard lock{queue_mutex_};
111
112 using work_type = decltype(function(params...));
113 auto return_type = std::make_shared<std::packaged_task<work_type()>>(packet);
114
115 std::future<work_type> f = return_type->get_future();
116 work_queue_.push([return_type](){(*return_type)();});
117 warner_job_avaliable_.notify_one();
118 return f;
119 }
120} // namespace Raftel
121
122#endif // __JOB_SYSTEM_H__
~JobSystem()
Destructor that ensures proper thread cleanup.
JobSystem()
Constructor that initializes worker threads.
static std::unique_ptr< JobSystem > make()
Factory method to create a JobSystem instance.
auto AddWork(MyJobFunction &&function, Arguments &&... params) -> std::future< decltype(function(params...))>
Deleted copy and move constructors/operators to prevent copying or moving.