gpt4 book ai didi

c++ - 如何使用模板化成员函数提交线程池(需要修改函数内部的成员)

转载 作者:行者123 更新时间:2023-11-28 05:39:33 24 4
gpt4 key购买 nike

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

我在这里看到了类似的问题,但仍然对它感到疑惑。一个相同的例子真的很有帮助。

非常感谢您的帮助。

最佳答案

你可以使用 lambda:

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

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

注意:你必须确保av存活的时间足够长。

关于c++ - 如何使用模板化成员函数提交线程池(需要修改函数内部的成员),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37460589/

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