【发布时间】:2016-05-18 06:58:58
【问题描述】:
我正在尝试使用 Anthony Williams “C++ Concurrency in Action”一书中的一个简单线程池示例。我什至在其中一篇文章中找到了代码(类 thread_pool): Synchronizing tasks 但我有一个不同的问题。我想用以下签名向队列提交一个任务(一个成员函数):
class A;
class B;
bool MyClass::Func(A*, B*);
我需要如何更改 thread_pool 类,或者如何将我的函数打包到一些 void F() 中,假设它被用作任务在这个例子中? 这是对我来说最相关的课程部分(详细信息请参见上面的链接):
class thread_pool
{
thread_safe_queue<std::function<void()> work_queue; // bool MyClass::Func(a,b) ??
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 should bool MyClassFunc(A*, B*) be submitted here
}
}
最后,如何在我的代码中调用提交函数?
非常感谢您的帮助(不幸的是,我在使用所有 C++11 功能方面还不是很有经验,这可能也是我在这里需要帮助的原因,但这个问题的答案将是开始:))。
【问题讨论】:
标签: multithreading c++11 threadpool