啊哈!看起来你在搞多线程的线程池,有点猛哦,代码写到这一步已经很不错了。我们来看看为什么会报那个神秘的C3520错误吧。
这个错误一般是因为参数包展开(variadic templates)过程中出了些问题。请注意一下你 `enqueue` 方法中的参数绑定部分。让我来帮你找出问题,并修正一下。
首先,这里有几个小问题需要解决:
1. **参数模板定义**:你的 `enqueue` 方法参数模板定义不正确。
2. **启用using声明和std前缀补全**:代码中少了很多标准库头文件,只补全了一部分。
3. **对线程的 join 应该是对单个线程进行的**。
来看看完整的解决方案:
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- #include <functional>
- #include <utility> // 为 std::forward
- class ThreadPool
- {
- public:
- ThreadPool(int numThread) : stop(false)
- {
- for (size_t i = 0; i < numThread; ++i)
- {
- threads.emplace_back(
- [this]()
- {
- while (1)
- {
- std::function<void()> task;
- {
- std::unique_lock<std::mutex> lock(this->mtx);
- this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
- if (this->stop && this->tasks.empty())
- return;
- task = std::move(this->tasks.front());
- this->tasks.pop();
- }
- task();
- }
- });
- }
- }
- ~ThreadPool()
- {
- {
- std::unique_lock<std::mutex> lock(mtx);
- stop = true;
- }
- condition.notify_all();
- for (std::thread &thread : threads)
- {
- thread.join();
- }
- }
-
- template<typename F, typename... Args>
- void enqueue(F&& f, Args&&... args)
- {
- auto task = std::make_shared<std::function<void()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
- {
- std::unique_lock<std::mutex> lock(mtx);
- tasks.push([task]() { (*task)(); });
- }
- 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 running." << std::endl;
- });
- }
- std::this_thread::sleep_for(std::chrono::seconds(2)); // 给点时间让任务执行
- return 0;
- }
复制代码
解释一下:
1. **`mtx`加锁**:我们使用 `std::unique_lock<std::mutex>` 而不是直接的 `std::unique_lock`,以确保与对象关联。
2. **参数包展开**:在 `enqueue` 方法里,我们通过 `std::bind` 和 `std::forward` 来正确地封装和转发参数,保持函数的完美转发。
3. **通知一个线程**:我们在添加任务后通知一个线程 `condition.notify_one()` 而不是 `notify_all()`,提高效率。
改进之后,这段代码应该能顺利运行了!祝你多线程编程愉快,就像吃薯片一样轻松!(虽然其实一点都不轻松……)
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。