hoshi-lang dev
Yet another programming language
Loading...
Searching...
No Matches
codegenTaskDispatcher.cpp
Go to the documentation of this file.
1//
2// Created by XIaokang00010 on 2026/2/8.
3//
4
6
7namespace yoi {
8
10 // automatically use hardware cores from system info
11 if (threadCount == 0)
12 threadCount = std::thread::hardware_concurrency();
13 // threadCount = 1;
14 for (size_t i = 0; i < threadCount; ++i) {
15 workers.emplace_back(&CodegenTaskDispatcher::workerLoop, this);
16 }
17 }
18
20 {
21 std::unique_lock<std::mutex> lock(queueMutex);
22 stop = true;
23 }
24 queueCondition.notify_all();
25 for (std::thread &worker : workers) {
26 if (worker.joinable()) {
27 worker.join();
28 }
29 }
30 }
31
32 void CodegenTaskDispatcher::dispatch(std::function<void()> task) {
33 {
34 std::unique_lock<std::mutex> lock(queueMutex);
36 taskQueue.push(std::move(task));
37 }
38 queueCondition.notify_one();
39 }
40
42 std::unique_lock<std::mutex> lock(waitMutex);
43 waitCondition.wait(lock, [this]() { return activeTasks == 0; });
44 }
45
47 while (true) {
48 std::function<void()> task;
49 {
50 std::unique_lock<std::mutex> lock(queueMutex);
51 queueCondition.wait(lock, [this]() { return stop || !taskQueue.empty(); });
52 if (stop && taskQueue.empty()) {
53 return;
54 }
55 task = std::move(taskQueue.front());
56 taskQueue.pop();
57 }
58
59 task();
60
61 {
62 std::unique_lock<std::mutex> lock(waitMutex);
64 if (activeTasks == 0) {
65 waitCondition.notify_all();
66 }
67 }
68 }
69 }
70
71} // namespace yoi
std::condition_variable queueCondition
void dispatch(std::function< void()> task)
Dispatch a task to the thread pool.
std::queue< std::function< void()> > taskQueue
void wait()
Wait for all dispatched tasks to complete.
std::vector< std::thread > workers
CodegenTaskDispatcher(size_t threadCount=0)
std::condition_variable waitCondition