gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:17:08 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com