c++ - 如何使用模板化成员函数提交线程池(需要修改函数内部的成员)

标签 c++ multithreading c++11 threadpool

我正在尝试重新使用 SO 中提到的简单线程池 -

class thread_pool 
{
      thread_safe_queue<std::function<void()> work_queue; // need to submit  fun(v) of class A where v is vector<string> here.

  void worker_thread() {
       while(!done)
       {         
           std::function<void()> task;
           if(work_queue.try_pop(task)) 
           {
               task();  // how should my function MyClass::Func(a,b) be called here?                    
           }
          else 
          {
              std::this_thread::yield();
          }
      }
  }
  // -- Submit a task to the thread pool
  template <typename FunctionType>
  void submit(FunctionType f) {
  work_queue.push(std::function<void()>(f)); //how do i submit something like A.fun(v) ?
 }

现在我需要提交一个任务,它是队列中模板化类的成员函数

template<class T>
class A
{
private:
int x ;
public:
    void fun(std::vector<std::string> & items) 
    {
        //do somehting with items.
         x = 5; // modify the members.
    }// please note that i need to modify members in this function in submitted thread.
};

所以最后我需要类似的东西-

thread_pool tp;
// a member function of class obj A (a) submitted with vector<string> v.
tp.submit(&A<int>::fun, std::ref(a), v);

我的疑问是任务队列签名看起来如何执行上述任务? 我需要如何更改 thread_pool 类才能运行此模板化成员函数?如何在我的代码中调用提交函数?

我在这里看到了类似的问题,但仍然对它感到疑惑。 一个相同的例子真的很有帮助。

非常感谢您的帮助。

最佳答案

你可以使用 lambda:

thread_pool tp;
A<int> a;
td::vector<std::string> v;

tp.submit([&]() { a.fun(v); });

注意:你必须确保av存活的时间足够长。

关于c++ - 如何使用模板化成员函数提交线程池(需要修改函数内部的成员),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37460589/

相关文章:

c++ - 检查统一数据的最佳方法是什么?

c++ - 如何以编程方式将路由添加到网络接口(interface)

c# - 如何为C++、protobuf制作swig接口(interface)文件

c++ - 更改 malloc 函数分配空间

循环内的 C++ std::thread 同步

创建和销毁线程

c++ - std::array 的内联初始化有什么问题?

c# - C# 中的 RSA 签名和 C++ 中的 Crypto++ 验证

Google Datastore 中使用游标的多线程

C++11 值初始化器与列表初始化器