哎呀,鱼油,好像你的代码有点问题啊!还是让我帮你瞧瞧看哪里出了错。我们先来逐步拆解一下。
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <mutex>
- #include <condition_variable>
- #include <functional>
- #include <thread>
- class ThreadPool {
- public:
- ThreadPool(int numThread) : stop(false) {
- for (size_t i = 0; i < numThread; i++) {
- threads.emplace_back([this]() {
- while (true) {
- std::function<void()> task;
- {
- std::unique_lock<std::mutex> lock(mtx);
- condition.wait(lock, [this] { return !tasks.empty() || stop; });
- if (stop && tasks.empty()) {
- return;
- }
- task = std::move(tasks.front());
- tasks.pop();
- }
- task();
- }
- });
- }
- }
- ~ThreadPool() {
- {
- std::unique_lock<std::mutex> lock(mtx);
- stop = true;
- }
- condition.notify_all();
- for (std::thread &worker : threads) {
- worker.join();
- }
- }
- template<class F, class... Args>
- void enqueue(F&& f, Args&&... args) {
- {
- std::unique_lock<std::mutex> lock(mtx);
- tasks.emplace([f, args...]() { f(args...); });
- }
- condition.notify_one();
- }
- private:
- std::vector<std::thread> threads;
- std::queue<std::function<void()>> tasks;
- std::mutex mtx;
- std::condition_variable condition;
- bool stop;
- };
- int main() {
- ThreadPool pool(4);
- for (size_t i = 0; i < 10; i++) {
- pool.enqueue([i]() {
- std::cout << "Task " << i << " is executing\n";
- });
- }
- std::this_thread::sleep_for(std::chrono::seconds(2));
- return 0;
- }
复制代码
几点注意的地方:
1. `#include`部分,有些标准头文件没加上,比如 `<iostream>` 和 `<functional>`。
2. `std::unique_lock`需要传递锁类型。
3. 析构函数中应使用 `std::unique_lock` 在修改 `stop` 标志位时锁住 `mtx`,然后调用 `notify_all()` 唤醒所有线程以便它们能退出。
4. 修正了 `enqueue` 函数模板参数格式,并在卧槽确保对 `condition` 使用 `notify_one` 而不是 `notify_all`,这样可以减少不必要的唤醒。
代码经过这些调整后,相信应该能正常运行了。如果有其他问题,尽管问!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。