【发布时间】: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([&] { a.fun(v); }); -
谢谢。它奏效了。
标签: c++ multithreading c++11 threadpool