multithreading - C++11线程池——带输入参数的任务

标签 multithreading c++11 threadpool

我正在尝试使用 Anthony Williams “C++ Concurrency in Action”一书中的一个简单线程池示例。我什至在其中一篇文章中找到了代码(线程池类):
Synchronizing tasks
但我有一个不同的问题。我想使用以下签名将任务(成员函数)提交到队列:

class A;
class B;
bool MyClass::Func(A*, B*); 

我需要如何更改 thread_pool 类,或者如何将我的函数打包到某个 void F() 中,假设在此示例中将其用作任务?
这是对我来说最相关的类(class)部分(详细信息请参见上面的链接):
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 功能方面还不是很有经验,这可能也是我在这里需要帮助的原因,但这个问题的答案将是开始的:)) .

最佳答案

当您将任务插入队列时,您必须将参数绑定(bind)到一个值。这意味着您必须为您的函数创建一个包装器来存储 this 的值。以及两个函数参数的值。有很多方法可以做到这一点,例如lambda 函数或 std::bind .

work_queue.push_back( [obj, a, b]() {obj->Func(a,b)} );
work_queue.push_back( std::bind(&MyClass::Func, obj, a, b) );

您的提交函数必须采用这些参数并创建绑定(bind),例如
template<typename F, typename... Args>
void submit(F f, Args&&... args) {
    work_queue.push_back( std::bind(f, std::forward<Args>(args)...) );
}

为成员函数和对象创建一个特殊的重载可能很方便。

关于multithreading - C++11线程池——带输入参数的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37292342/

相关文章:

c++ - 对象的销毁是否正确发生?

c++ - 以下代码片段 C++ 的说明

c++ - c++ shared_ptr中的相互破坏

java - 将任务划分为线程 - 多线程

java - Akka 如何从 ForkJoinPool 中获益?

java - Javafx:javafx.concurrent和Platform.runLater之间的区别?

python - 根据 celery 的结果路由到 worker ?

c# - 抛出System.OutOfMemoryException'-WebClient.DownloadStringAsynch()

具有后台线程的 Java WebSocket

multithreading - Delphi - OTL - ThreadPool 和 Worker 线程之间的通信