I’ve wrote a ThreadPool implementation in C# and now I would like to port it into standard C++ (with boost if possible). The original C# version can call functions with multiple arguments using delegates, and the code is something like:
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:
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 *). 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?
You could use boost’s
bindto generate nullary functions. It would be somewhat verbose, but instead of callingRunOrBlock(f, a1, a2, ...)you could doRunOrBlock(bind(f, a1, a2, ...)).