Implement ThreadPool, which can call functions with multiple arguments in C ++

I wrote an implementation of ThreadPool in C #, and now I would like to put it in standard C ++ (with the possibility of increasing, if possible). The original version of C # can call functions with multiple arguments using delegates, and the code is something like this:

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, the "Function" is defined using the 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 read some material for pThread and knew that you could declare these arguments in a structure and then include it in (void *). However, since most of my functions are already implemented, it would be extremely inconvenient to use this method.

My question is: since C ++ does not have delegate support, what is a convenient and convenient way to implement a thread pool that supports calling functions with multiple arguments?

+4
source share
2 answers

You can use boost bind to create null functions. That would be somewhat verbose, but instead of calling RunOrBlock(f, a1, a2, ...) you could do RunOrBlock(bind(f, a1, a2, ...)) .

+4
source

Pretty sure the only "good" way to do this is to use C ++ 11 variable templates. For example :.

 template <typename RetType, typename Function, typename... Args> RetType CallFunc(Func f, Args... args) { return f(args...); } 

Otherwise, you will have to write several versions for 1 argument, 2 arguments, 3 arguments, etc. or use some kind of black magic that will be unsafe or intolerable.

+2
source

Source: https://habr.com/ru/post/1381399/


All Articles