mrDarker
2025-07-09 8364edfb293e9e31e0fa7899bedcef9cd393e130
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "StdAfx.h"
#include "ThreadPool.h"
 
ThreadPool::ThreadPool(size_t thread_count) : m_stop(false) {
    for (size_t i = 0; i < thread_count; ++i) {
        m_threads.emplace_back(&ThreadPool::worker_thread, this);
    }
}
 
ThreadPool::~ThreadPool() {
    {
        std::unique_lock<std::mutex> lock(m_queue_mutex);
        m_stop = true;
    }
    m_cv.notify_all();
    for (std::thread& worker : m_threads) {
        if (worker.joinable()) {
            worker.join();
        }
    }
}
 
void ThreadPool::worker_thread() {
    while (true) {
        std::function<void()> task;
        {
            std::unique_lock<std::mutex> lock(m_queue_mutex);
            m_cv.wait(lock, [this]() { return m_stop || !m_tasks.empty(); });
            if (m_stop && m_tasks.empty()) {
                return;
            }
            task = std::move(m_tasks.front());
            m_tasks.pop();
        }
        task();
    }
}