[英]Implement a ThreadPool which can call functions with multiple arguments in C++
I've wrote a ThreadPool implementation in C# and now I would like to port it into standard C++ (with boost if possible). 我在C#中编写了一个ThreadPool实现,现在我想将它移植到标准C ++中(如果可能的话,使用boost)。 The original C# version can call functions with multiple arguments using delegates, and the code is something like:
原始的C#版本可以使用委托来调用具有多个参数的函数,代码类似于:
public static void RunOrBlock(Function function)
{
WorkItem workItem = new WorkItemNoArguments(function);
RunOrBlock(workItem);
}
public static void RunOrBlock<T1>(Function<T1> function, T1 t1)
{
WorkItem workItem = new WorkItem<T1>(function, t1);
RunOrBlock(workItem);
}
Here a "Function" is defined using delegate: 这里使用委托定义“函数”:
public delegate void Function();
public delegate void Function<in T1>(T1 t1);
And WorkItem can be defined similarly: WorkItem可以类似地定义:
public abstract class WorkItem
{
protected int threadIndex;
public int ThreadIndex
{
get { return threadIndex; }
set { threadIndex = value; }
}
public abstract void Run();
}
public class WorkItem<T1> : WorkItem
{
private readonly Function<T1> _function;
private readonly T1 _t1;
public WorkItem(Function<T1> function, T1 t1)
{
_function = function;
_t1 = t1;
}
public override void Run()
{
_function(_t1);
}
}
I've read some materials for pThread and have known that it is possible to declare these arguments in a struct and then cast it into (void *). 我已经阅读了pThread的一些材料,并且已经知道可以在结构中声明这些参数然后将其转换为(void *)。 However, since most of my functions have already been implemented it would be extremely inconvenient using this way.
但是,由于我的大部分功能已经实现,因此使用这种方式会非常不方便。
My question is: since C++ does not have delegate support, what is a handy and convenient way to implement a thread pool which supports calling functions with multiple arguments? 我的问题是:由于C ++没有委托支持,实现支持使用多个参数调用函数的线程池有什么方便和方便的方法?
You could use boost's bind
to generate nullary functions. 您可以使用boost的
bind
来生成nullary函数。 It would be somewhat verbose, but instead of calling RunOrBlock(f, a1, a2, ...)
you could do RunOrBlock(bind(f, a1, a2, ...))
. 它有点冗长,但不是调用
RunOrBlock(f, a1, a2, ...)
而是可以运行RunOrBlock(bind(f, a1, a2, ...))
。
Pretty sure the only "good" way to do it is to use C++11 variadic templates. 非常肯定唯一“好”的方法是使用C ++ 11可变参数模板。 Eg:
例如:
template <typename RetType, typename Function, typename... Args>
RetType CallFunc(Func f, Args... args)
{
return f(args...);
}
Otherwise you'll have to write multiple versions for 1 argument, 2 arguments, 3 arguments etc., or use some kind of black magic that'll be unsafe or not portable. 否则你将不得不为1个参数,2个参数,3个参数等编写多个版本,或使用某种不安全或不可移植的黑魔法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.