group2 0.1.0
CSE 125 Group 2
Loading...
Searching...
No Matches
WorkerPool.hpp
Go to the documentation of this file.
1
13
14#pragma once
15
16#include <atomic>
17#include <condition_variable>
18#include <cstddef>
19#include <functional>
20#include <mutex>
21#include <thread>
22#include <vector>
23
25{
26public:
32 explicit WorkerPool(int numWorkers);
33
35
36 WorkerPool(const WorkerPool&) = delete;
37 WorkerPool& operator=(const WorkerPool&) = delete;
40
42 [[nodiscard]] int numWorkers() const noexcept { return static_cast<int>(workers_.size()); }
43
55 void parallelFor(int count, const std::function<void(int begin, int end)>& fn);
56
57private:
58 void workerLoop(int workerId);
59
60 std::vector<std::thread> workers_;
61
62 // Job hand-off state. The main thread sets `currentFn_` + `currentTotal_`
63 // + `currentChunkSize_` + bumps `generation_`, then notifies all workers.
64 // Each worker grabs its `workerId` chunk. When all workers (and the
65 // caller's inline chunk) finish, `outstanding_` reaches zero and the
66 // caller is unblocked.
67 std::mutex mtx_;
68 std::condition_variable cvWork_;
69 std::condition_variable cvDone_;
70 const std::function<void(int, int)>* currentFn_ = nullptr;
74 std::atomic<int> outstanding_{0};
75 std::atomic<bool> stop_{false};
76};
const std::function< void(int, int)> * currentFn_
Definition WorkerPool.hpp:70
int currentGeneration_
Definition WorkerPool.hpp:73
WorkerPool(int numWorkers)
Spin up numWorkers persistent threads.
Definition WorkerPool.cpp:9
WorkerPool(const WorkerPool &)=delete
std::vector< std::thread > workers_
Definition WorkerPool.hpp:60
WorkerPool & operator=(const WorkerPool &)=delete
int currentChunkSize_
Definition WorkerPool.hpp:72
WorkerPool & operator=(WorkerPool &&)=delete
std::condition_variable cvDone_
Definition WorkerPool.hpp:69
int currentTotal_
Definition WorkerPool.hpp:71
int numWorkers() const noexcept
Number of worker threads (excluding the calling thread).
Definition WorkerPool.hpp:42
std::atomic< int > outstanding_
Definition WorkerPool.hpp:74
void parallelFor(int count, const std::function< void(int begin, int end)> &fn)
Run fn in parallel over the index range [0, count).
Definition WorkerPool.cpp:31
std::mutex mtx_
Definition WorkerPool.hpp:67
std::condition_variable cvWork_
Definition WorkerPool.hpp:68
std::atomic< bool > stop_
Definition WorkerPool.hpp:75
WorkerPool(WorkerPool &&)=delete
~WorkerPool()
Definition WorkerPool.cpp:18
void workerLoop(int workerId)
Definition WorkerPool.cpp:89