Wildmeshing Toolkit
Loading...
Searching...
No Matches
task_group.hpp
1#pragma once
2
3#include <exception>
4#include <mutex>
5#include <thread>
6#include <vector>
7
8namespace wmtk::threading {
9
10// ---------------------------------------------------------------------------
11// task_group: replaces tbb::task_group. Each run() spawns a thread; wait() joins.
12// ---------------------------------------------------------------------------
14{
15 std::vector<std::thread> m_threads;
16 std::exception_ptr m_eptr;
17 std::mutex m_eptr_mutex;
18
19public:
20 task_group() = default;
21 task_group(const task_group&) = delete;
22 task_group& operator=(const task_group&) = delete;
23
24 template <typename F>
25 void run(F&& f)
26 {
27 m_threads.emplace_back([this, f = std::forward<F>(f)]() mutable {
28 try {
29 f();
30 } catch (...) {
31 std::lock_guard<std::mutex> lock(m_eptr_mutex);
32 if (!m_eptr) {
33 m_eptr = std::current_exception();
34 }
35 }
36 });
37 }
38
39 void wait()
40 {
41 for (auto& t : m_threads) {
42 if (t.joinable()) {
43 t.join();
44 }
45 }
46 m_threads.clear();
47 if (m_eptr) {
48 std::exception_ptr e = m_eptr;
49 m_eptr = nullptr;
50 std::rethrow_exception(e);
51 }
52 }
53
55 {
56 for (auto& t : m_threads) {
57 if (t.joinable()) {
58 t.join();
59 }
60 }
61 }
62};
63
64} // namespace wmtk::threading
Definition task_group.hpp:14