jfc-dispatch 18e7bb6f85b339b00e44676aaf53d863235bab2b
Loading...
Searching...
No Matches
dispatch.h
1// © Joseph Cameron - MIT License
2
3#ifndef JFC_DISPATCH_H
4#define JFC_DISPATCH_H
5
6#include <cstddef>
7#include <exception>
8#include <functional>
9#include <mutex>
10#include <utility>
11#include <vector>
12
13namespace jfc::dispatch {
14 using chunk_type = std::function<void(std::size_t aChunkIndex)>;
15
18 using task_dispatcher_type = std::function<void(std::size_t aChunkCount, const chunk_type &aChunk)>;
19
20 using task_type = std::function<void()>;
21
22 using task_submitter_type = std::function<void(std::vector<task_type> &&aTasks)>;
23
26 inline void run(const task_dispatcher_type &aDispatcher, const std::size_t aCount, const chunk_type &aChunk) {
27 if (!aCount) return;
28
29 std::exception_ptr failure;
30
31 if (!aDispatcher || aCount == 1) {
32 for (std::size_t i = 0; i < aCount; ++i) {
33 try {
34 aChunk(i);
35 }
36 catch (...) {
37 if (!failure) failure = std::current_exception();
38 }
39 }
40 }
41 else {
42 std::mutex failing;
43
44 aDispatcher(aCount, [&](const std::size_t aIndex) {
45 try {
46 aChunk(aIndex);
47 }
48 catch (...) {
49 const std::lock_guard lock(failing);
50
51 if (!failure) failure = std::current_exception();
52 }
53 });
54 }
55
56 if (failure) std::rethrow_exception(failure);
57 }
58
61 inline void run_inline(std::vector<task_type> &&aTasks) {
62 std::exception_ptr failure;
63
64 for (auto &each : aTasks) {
65 try {
66 each();
67 }
68 catch (...) {
69 if (!failure) failure = std::current_exception();
70 }
71 }
72
73 if (failure) std::rethrow_exception(failure);
74 }
75
76 template <typename pool_type>
77 [[nodiscard]] task_dispatcher_type dispatcher_of(pool_type &aPool) {
78 return [&aPool](const std::size_t aCount, const chunk_type &aChunk) { aPool.run_and_wait(aCount, aChunk); };
79 }
80
81 template <typename pool_type>
82 [[nodiscard]] task_submitter_type submitter_of(pool_type &aPool) {
83 return [&aPool](std::vector<task_type> &&aTasks) { aPool.add_tasks(std::move(aTasks)); };
84 }
85}
86
87#endif