Coverage Report

Created: 2026-11-07 16:24

/home/runner/work/LabNeura/LabNeura/src/labneura/parallel.cpp
Line
Count
Source (jump to first uncovered line)
1
#include "labneura/runtime.h"
2
3
#include <algorithm>
4
#include <atomic>
5
#include <condition_variable>
6
#include <cstdint>
7
#include <exception>
8
#include <memory>
9
#include <mutex>
10
#include <stdexcept>
11
#include <thread>
12
#include <utility>
13
#include <vector>
14
15
namespace labneura {
16
namespace {
17
18
thread_local unsigned parallel_callback_depth = 0;
19
20
class CallbackScope {
21
public:
22
0
    CallbackScope() { ++parallel_callback_depth; }
23
0
    ~CallbackScope() { --parallel_callback_depth; }
24
25
    CallbackScope(const CallbackScope&) = delete;
26
    CallbackScope& operator=(const CallbackScope&) = delete;
27
};
28
29
void run_synchronously(
30
    std::size_t begin, std::size_t end, std::size_t grain_size,
31
0
    const std::function<void(std::size_t, std::size_t)>& function) {
32
0
    for (std::size_t chunk_begin = begin; chunk_begin < end;) {
33
0
        const std::size_t chunk_length =
34
0
            std::min(grain_size, end - chunk_begin);
35
0
        CallbackScope scope;
36
0
        function(chunk_begin, chunk_begin + chunk_length);
37
0
        chunk_begin += chunk_length;
38
0
    }
39
0
}
40
41
struct Job {
42
    Job(std::size_t range_begin, std::size_t range_end, std::size_t chunk_size,
43
        const std::function<void(std::size_t, std::size_t)>& callback,
44
        std::size_t worker_count)
45
0
        : begin(range_begin),
46
0
          length(range_end - range_begin),
47
0
          grain_size(chunk_size),
48
0
          chunks(1 + (length - 1) / grain_size),
49
0
          function(callback),
50
0
          workers_remaining(worker_count) {}
51
52
0
    void run_chunks() noexcept {
53
0
        while (!cancelled.load(std::memory_order_relaxed)) {
54
0
            const std::size_t chunk =
55
0
                next_chunk.fetch_add(1, std::memory_order_relaxed);
56
0
            if (chunk >= chunks) return;
57
58
0
            const std::size_t offset = chunk * grain_size;
59
0
            const std::size_t chunk_begin = begin + offset;
60
0
            const std::size_t chunk_length =
61
0
                std::min(grain_size, length - offset);
62
0
            try {
63
0
                CallbackScope scope;
64
0
                function(chunk_begin, chunk_begin + chunk_length);
65
0
            } catch (...) {
66
0
                {
67
0
                    std::lock_guard<std::mutex> lock(exception_mutex);
68
0
                    if (!exception) exception = std::current_exception();
69
0
                }
70
0
                cancelled.store(true, std::memory_order_relaxed);
71
0
                return;
72
0
            }
73
0
        }
74
0
    }
75
76
0
    void worker_finished() {
77
0
        std::lock_guard<std::mutex> lock(completion_mutex);
78
0
        if (--workers_remaining == 0) completion_cv.notify_one();
79
0
    }
80
81
0
    void wait_for_workers() {
82
0
        std::unique_lock<std::mutex> lock(completion_mutex);
83
0
        completion_cv.wait(lock, [this] { return workers_remaining == 0; });
84
0
    }
85
86
0
    void rethrow_if_failed() const {
87
0
        std::lock_guard<std::mutex> lock(exception_mutex);
88
0
        if (exception) std::rethrow_exception(exception);
89
0
    }
90
91
    const std::size_t begin;
92
    const std::size_t length;
93
    const std::size_t grain_size;
94
    const std::size_t chunks;
95
    const std::function<void(std::size_t, std::size_t)>& function;
96
    std::atomic<std::size_t> next_chunk{0};
97
    std::atomic<bool> cancelled{false};
98
    mutable std::mutex exception_mutex;
99
    std::exception_ptr exception;
100
    std::mutex completion_mutex;
101
    std::condition_variable completion_cv;
102
    std::size_t workers_remaining;
103
};
104
105
class ThreadPool {
106
public:
107
0
    ~ThreadPool() { stop_workers(); }
108
109
    void execute(std::size_t begin, std::size_t end, std::size_t grain_size,
110
                 const std::function<void(std::size_t, std::size_t)>& function,
111
0
                 std::size_t thread_count) {
112
0
        std::unique_lock<std::mutex> submission_lock(submission_mutex);
113
114
0
        if (thread_count <= 1 || end - begin <= grain_size ||
115
0
            parallel_callback_depth != 0) {
116
0
            run_synchronously(begin, end, grain_size, function);
117
0
            return;
118
0
        }
119
120
0
        ensure_workers(thread_count - 1);
121
0
        auto job = std::make_shared<Job>(begin, end, grain_size, function,
122
0
                                         workers.size());
123
0
        {
124
0
            std::lock_guard<std::mutex> lock(state_mutex);
125
0
            current_job = job;
126
0
            ++generation;
127
0
        }
128
0
        work_cv.notify_all();
129
130
0
        job->run_chunks();
131
0
        job->wait_for_workers();
132
0
        job->rethrow_if_failed();
133
0
    }
134
135
private:
136
0
    void ensure_workers(std::size_t desired_count) {
137
0
        if (workers.size() == desired_count) return;
138
0
        stop_workers();
139
0
        try {
140
0
            workers.reserve(desired_count);
141
0
            for (std::size_t i = 0; i < desired_count; ++i) {
142
0
                workers.emplace_back([this] { worker_loop(); });
143
0
            }
144
0
        } catch (...) {
145
0
            stop_workers();
146
0
            throw;
147
0
        }
148
0
    }
149
150
0
    void stop_workers() noexcept {
151
0
        {
152
0
            std::lock_guard<std::mutex> lock(state_mutex);
153
0
            stopping = true;
154
0
        }
155
0
        work_cv.notify_all();
156
0
        for (auto& worker : workers) {
157
0
            if (worker.joinable()) worker.join();
158
0
        }
159
0
        workers.clear();
160
0
        {
161
0
            std::lock_guard<std::mutex> lock(state_mutex);
162
0
            current_job.reset();
163
0
            generation = 0;
164
0
            stopping = false;
165
0
        }
166
0
    }
167
168
0
    void worker_loop() {
169
0
        std::uint64_t observed_generation = 0;
170
0
        std::unique_lock<std::mutex> lock(state_mutex);
171
0
        while (true) {
172
0
            work_cv.wait(lock, [this, observed_generation] {
173
0
                return stopping || generation != observed_generation;
174
0
            });
175
0
            if (stopping) return;
176
177
0
            observed_generation = generation;
178
0
            const auto job = current_job;
179
0
            lock.unlock();
180
0
            job->run_chunks();
181
0
            job->worker_finished();
182
0
            lock.lock();
183
0
        }
184
0
    }
185
186
    std::mutex submission_mutex;
187
    std::mutex state_mutex;
188
    std::condition_variable work_cv;
189
    std::vector<std::thread> workers;
190
    std::shared_ptr<Job> current_job;
191
    std::uint64_t generation{0};
192
    bool stopping{false};
193
};
194
195
0
ThreadPool& thread_pool() {
196
0
    static ThreadPool pool;
197
0
    return pool;
198
0
}
199
200
}  // namespace
201
202
void parallel_for(
203
    std::size_t begin, std::size_t end, std::size_t grain_size,
204
0
    const std::function<void(std::size_t, std::size_t)>& function) {
205
0
    if (grain_size == 0) {
206
0
        throw std::invalid_argument("parallel_for grain_size must be positive");
207
0
    }
208
0
    if (end < begin) {
209
0
        throw std::invalid_argument("parallel_for end must not precede begin");
210
0
    }
211
0
    if (begin == end) return;
212
0
    if (!function) {
213
0
        throw std::invalid_argument("parallel_for function must be callable");
214
0
    }
215
216
0
    const std::size_t thread_count = execution_thread_count();
217
0
    if (thread_count <= 1 || end - begin <= grain_size ||
218
0
        parallel_callback_depth != 0) {
219
0
        run_synchronously(begin, end, grain_size, function);
220
0
        return;
221
0
    }
222
0
    thread_pool().execute(begin, end, grain_size, function, thread_count);
223
0
}
224
225
}  // namespace labneura