鱼C论坛

 找回密码
 立即注册
查看: 994|回复: 3

[已解决]多线程模板问题

[复制链接]
发表于 2024-7-19 15:12:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
请问一下报错E:\my_project\线程8:线程池\线程8:线程池\线程8:线程池.cpp(60,47): error C3520: “Args”: 必须在此上下文中扩展参数包是怎么回事?
  1. #include <iostream>
  2. #include <thread>
  3. #include <condition_variable>
  4. #include <mutex>
  5. #include <queue>
  6. #include <vector>
  7. #include <functional>
  8. class ThreadPool
  9. {

  10. public:
  11.         ThreadPool(int numThread) :stop(false)
  12.         {
  13.                 for (size_t i = 0; i < numThread; i++)
  14.                 {
  15.                         threads.emplace_back(
  16.                         [this]()
  17.                         {
  18.                                 while (1)
  19.                                 {
  20.                                         std::unique_lock<std::mutex> lock(mtx);
  21.                                         condition.wait(lock, [this]() {return !tasks.empty()||stop; });
  22.                                         if (stop && tasks.empty())
  23.                                         {
  24.                                                 return 0;
  25.                                         }

  26.                                         std::function<void()> task(std::move(tasks.front()));
  27.                                         tasks.pop();
  28.                                         lock.unlock();

  29.                                         task();

  30.                                 }
  31.                         });
  32.                 }
  33.         }

  34.         ~ThreadPool()
  35.         {
  36.                 std::unique_lock<std::mutex> lock(mtx);
  37.                 stop = true;
  38.                 condition.notify_all();

  39.                 size_t t =  threads.size();

  40.                 for (size_t i = 0; i < t; i++)
  41.                 {
  42.                         threads[i].join();
  43.                 }


  44.         }

  45.         template<class F,class ...Args>
  46.         void enqueue(F&& f,Args&&... args)
  47.         {
  48.                
  49.                 std::function<void()> task =
  50.                          std::bind(std::forward<F>(f),std::forward<Args>(args...));

  51.                 {
  52.                         std::unique_lock<std::mutex> lock(mtx);
  53.                         tasks.emplace(std::move(task));
  54.                 }

  55.                 condition.notify_all();
  56.         }
  57. private:
  58.         std::vector<std::thread> threads;
  59.         std::queue<std::function<void()>> tasks;

  60.         std::mutex mtx;
  61.         std::condition_variable condition;

  62.         bool stop;
  63. };



  64. int main()
  65. {
  66.         ThreadPool pool(4);

  67.         for (size_t i = 0; i < 10; i++)
  68.         {
  69.                 pool.enqueue([i]() {
  70.                         std::cout << "task:" << i << "running..." << '\n';
  71.                         std::this_thread::sleep_for(std::chrono::seconds(1));
  72.                         std::cout << "task:" << i << "done" << '\n'; });
  73.         }

  74. }
复制代码
最佳答案
2024-7-19 15:13:43
啊哈!看起来你在搞多线程的线程池,有点猛哦,代码写到这一步已经很不错了。我们来看看为什么会报那个神秘的C3520错误吧。

这个错误一般是因为参数包展开(variadic templates)过程中出了些问题。请注意一下你 `enqueue` 方法中的参数绑定部分。让我来帮你找出问题,并修正一下。

首先,这里有几个小问题需要解决:

1. **参数模板定义**:你的 `enqueue` 方法参数模板定义不正确。
2. **启用using声明和std前缀补全**:代码中少了很多标准库头文件,只补全了一部分。
3. **对线程的 join 应该是对单个线程进行的**。

来看看完整的解决方案:

  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <thread>
  5. #include <mutex>
  6. #include <condition_variable>
  7. #include <functional>
  8. #include <utility> // 为 std::forward

  9. class ThreadPool
  10. {
  11. public:
  12.     ThreadPool(int numThread) : stop(false)
  13.     {
  14.         for (size_t i = 0; i < numThread; ++i)
  15.         {
  16.             threads.emplace_back(
  17.                 [this]()
  18.                 {
  19.                     while (1)
  20.                     {
  21.                         std::function<void()> task;
  22.                         {
  23.                             std::unique_lock<std::mutex> lock(this->mtx);
  24.                             this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
  25.                             if (this->stop && this->tasks.empty())
  26.                                 return;
  27.                             task = std::move(this->tasks.front());
  28.                             this->tasks.pop();
  29.                         }
  30.                         task();
  31.                     }
  32.                 });
  33.         }
  34.     }

  35.     ~ThreadPool()
  36.     {
  37.         {
  38.             std::unique_lock<std::mutex> lock(mtx);
  39.             stop = true;
  40.         }
  41.         condition.notify_all();
  42.         for (std::thread &thread : threads)
  43.         {
  44.             thread.join();
  45.         }
  46.     }

  47.     template<typename F, typename... Args>
  48.     void enqueue(F&& f, Args&&... args)
  49.     {
  50.         auto task = std::make_shared<std::function<void()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
  51.         {
  52.             std::unique_lock<std::mutex> lock(mtx);
  53.             tasks.push([task]() { (*task)(); });
  54.         }
  55.         condition.notify_one();
  56.     }

  57. private:
  58.     std::vector<std::thread> threads;
  59.     std::queue<std::function<void()>> tasks;
  60.    
  61.     std::mutex mtx;
  62.     std::condition_variable condition;
  63.     bool stop;
  64. };

  65. int main()
  66. {
  67.     ThreadPool pool(4);

  68.     for (size_t i = 0; i < 10; ++i)
  69.     {
  70.         pool.enqueue([i]
  71.         {
  72.             std::cout << "Task " << i << " is running." << std::endl;
  73.         });
  74.     }

  75.     std::this_thread::sleep_for(std::chrono::seconds(2)); // 给点时间让任务执行

  76.     return 0;
  77. }
复制代码


解释一下:

1. **`mtx`加锁**:我们使用 `std::unique_lock<std::mutex>` 而不是直接的 `std::unique_lock`,以确保与对象关联。
2. **参数包展开**:在 `enqueue` 方法里,我们通过 `std::bind` 和 `std::forward` 来正确地封装和转发参数,保持函数的完美转发。
3. **通知一个线程**:我们在添加任务后通知一个线程 `condition.notify_one()` 而不是 `notify_all()`,提高效率。

改进之后,这段代码应该能顺利运行了!祝你多线程编程愉快,就像吃薯片一样轻松!(虽然其实一点都不轻松……)

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-7-19 15:13:43 | 显示全部楼层    本楼为最佳答案   
啊哈!看起来你在搞多线程的线程池,有点猛哦,代码写到这一步已经很不错了。我们来看看为什么会报那个神秘的C3520错误吧。

这个错误一般是因为参数包展开(variadic templates)过程中出了些问题。请注意一下你 `enqueue` 方法中的参数绑定部分。让我来帮你找出问题,并修正一下。

首先,这里有几个小问题需要解决:

1. **参数模板定义**:你的 `enqueue` 方法参数模板定义不正确。
2. **启用using声明和std前缀补全**:代码中少了很多标准库头文件,只补全了一部分。
3. **对线程的 join 应该是对单个线程进行的**。

来看看完整的解决方案:

  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <thread>
  5. #include <mutex>
  6. #include <condition_variable>
  7. #include <functional>
  8. #include <utility> // 为 std::forward

  9. class ThreadPool
  10. {
  11. public:
  12.     ThreadPool(int numThread) : stop(false)
  13.     {
  14.         for (size_t i = 0; i < numThread; ++i)
  15.         {
  16.             threads.emplace_back(
  17.                 [this]()
  18.                 {
  19.                     while (1)
  20.                     {
  21.                         std::function<void()> task;
  22.                         {
  23.                             std::unique_lock<std::mutex> lock(this->mtx);
  24.                             this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
  25.                             if (this->stop && this->tasks.empty())
  26.                                 return;
  27.                             task = std::move(this->tasks.front());
  28.                             this->tasks.pop();
  29.                         }
  30.                         task();
  31.                     }
  32.                 });
  33.         }
  34.     }

  35.     ~ThreadPool()
  36.     {
  37.         {
  38.             std::unique_lock<std::mutex> lock(mtx);
  39.             stop = true;
  40.         }
  41.         condition.notify_all();
  42.         for (std::thread &thread : threads)
  43.         {
  44.             thread.join();
  45.         }
  46.     }

  47.     template<typename F, typename... Args>
  48.     void enqueue(F&& f, Args&&... args)
  49.     {
  50.         auto task = std::make_shared<std::function<void()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
  51.         {
  52.             std::unique_lock<std::mutex> lock(mtx);
  53.             tasks.push([task]() { (*task)(); });
  54.         }
  55.         condition.notify_one();
  56.     }

  57. private:
  58.     std::vector<std::thread> threads;
  59.     std::queue<std::function<void()>> tasks;
  60.    
  61.     std::mutex mtx;
  62.     std::condition_variable condition;
  63.     bool stop;
  64. };

  65. int main()
  66. {
  67.     ThreadPool pool(4);

  68.     for (size_t i = 0; i < 10; ++i)
  69.     {
  70.         pool.enqueue([i]
  71.         {
  72.             std::cout << "Task " << i << " is running." << std::endl;
  73.         });
  74.     }

  75.     std::this_thread::sleep_for(std::chrono::seconds(2)); // 给点时间让任务执行

  76.     return 0;
  77. }
复制代码


解释一下:

1. **`mtx`加锁**:我们使用 `std::unique_lock<std::mutex>` 而不是直接的 `std::unique_lock`,以确保与对象关联。
2. **参数包展开**:在 `enqueue` 方法里,我们通过 `std::bind` 和 `std::forward` 来正确地封装和转发参数,保持函数的完美转发。
3. **通知一个线程**:我们在添加任务后通知一个线程 `condition.notify_one()` 而不是 `notify_all()`,提高效率。

改进之后,这段代码应该能顺利运行了!祝你多线程编程愉快,就像吃薯片一样轻松!(虽然其实一点都不轻松……)

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-19 15:22:33 | 显示全部楼层
[code]    for (size_t i = 0; i < 10; ++i)
    {
        pool.enqueue([i]
        {
            std::cout << "Task " << i << " is running." << std::endl;
        });
    }
[/code咋啥也没有打印出来?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-7-19 15:23:56 | 显示全部楼层
sun_chuan 发表于 2024-07-19 15:22
for (size_t i = 0; i < 10; ++i)
    {
        po ...


哈哈,代码在高潮处戛然而止了,我帮你把它补全一下。

首先,你需要把 `std::cout` 的操作包围在一个 lambda 表达式里,然后传给线程池的 `enqueue` 方法。这样一来,线程池就可以执行这些任务了。

来看看补全后的代码吧:

  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <memory>
  5. #include <functional>
  6. #include <thread>
  7. #include <mutex>
  8. #include <condition_variable>  // 为 std::forward

  9. class ThreadPool
  10. {
  11. public:
  12.     ThreadPool(int numThread) : stop(false)
  13.     {
  14.         for (size_t i = 0; i < numThread; ++i)
  15.         {
  16.             threads.emplace_back(
  17.                 [this]()
  18.                 {
  19.                     while (1)
  20.                     {
  21.                         std::function<void()> task;
  22.                         {
  23.                             std::unique_lock<std::mutex> lock(this->mtx);
  24.                             this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); });
  25.                             if (this->stop && this->tasks.empty())
  26.                                 return;
  27.                             task = std::move(this->tasks.front());
  28.                             this->tasks.pop();
  29.                         }
  30.                         task();
  31.                     }
  32.                 });
  33.         }
  34.     }

  35.     ~ThreadPool()
  36.     {
  37.         {
  38.             std::unique_lock<std::mutex> lock(mtx);
  39.             stop = true;
  40.         }
  41.         condition.notify_all();
  42.         for (std::thread &thread : threads)
  43.         {
  44.             thread.join();
  45.         }
  46.     }

  47.     template<class F, class... Args>
  48.     void enqueue(F&& f, Args&&... args)
  49.     {
  50.         auto task = std::make_shared<std::packaged_task<void()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
  51.         {
  52.             std::unique_lock<std::mutex> lock(mtx);
  53.             tasks.push([task](){ (*task)(); });
  54.         }
  55.         condition.notify_one();
  56.     }

  57. private:
  58.     std::vector<std::thread> threads;
  59.     std::queue<std::function<void()>> tasks;
  60.    
  61.     std::mutex mtx;
  62.     std::condition_variable condition;
  63.     bool stop;
  64. };

  65. int main()
  66. {
  67.     ThreadPool pool(4);

  68.     for (size_t i = 0; i < 10; ++i)
  69.     {
  70.         pool.enqueue([i]
  71.         {
  72.             std::cout << "Task " << i << " is being processed" << std::endl;
  73.         });
  74.     }

  75.     std::this_thread::sleep_for(std::chrono::seconds(2)); // 延时,让所有任务有时间完成
  76.     return 0;
  77. }
复制代码


这样,主线程会创建多个任务,并将它们添加到线程池中,每个任务就是输出一行 `Task i is being processed`。程序末尾的 `std::this_thread::sleep_for` 只是为了确保所有任务都有时间运行完毕,可以根据需要调整或移除。

希望这能帮你解决问题,继续加油吧,未来的多线程大牛!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-10 09:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表