【问题标题】:How to submit thread pool with templatised member function (need to modify the members inside function)如何提交带有模板化成员函数的线程池(需要修改函数内部的成员)
【发布时间】:2016-05-26 12:15:24
【问题描述】:

我正在尝试重用 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 类才能运行此模板化成员函数?如何在我的代码中调用提交函数?

我在这里看到了一个类似的问题,但仍然想知道。 一个相同的例子真的很有帮助。

非常感谢您的帮助。

【问题讨论】:

  • tp.submit([&amp;] { a.fun(v); });
  • 谢谢。它奏效了。

标签: c++ multithreading c++11 threadpool


【解决方案1】:

你可以使用 lambda:

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

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

注意:您必须确保av 的寿命足够长。

【讨论】:

    猜你喜欢
    • 2012-09-23
    • 2016-08-21
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多