mrDarker
2025-07-16 1dbe46cd9d0f181d08d5a69f72d8548628a13b9d
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
38
#ifndef THREADPOOL_H
#define THREADPOOL_H
 
#include <vector>
#include <thread>
#include <queue>
#include <functional>
#include <future>
#include <mutex>
#include <condition_variable>
#include <iostream>
 
class ThreadPool {
public:
    explicit ThreadPool(size_t thread_count);
    ~ThreadPool();
 
    // 提交任务
    template<class F>
    void enqueue(F&& task) {
        {
            std::unique_lock<std::mutex> lock(m_queue_mutex);
            m_tasks.emplace(std::forward<F>(task));
        }
        m_cv.notify_one();
    }
 
private:
    void worker_thread();
 
    std::vector<std::thread> m_threads;
    std::queue<std::function<void()>> m_tasks;
    std::mutex m_queue_mutex;
    std::condition_variable m_cv;
    bool m_stop;
};
 
#endif // THREADPOOL_H