www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Thread sequencer

I'm wondering if there is an easy way to create a single extra 
thread that one can pass delegates(code) to and it executes it 
properly. The thread never closes except at shutdown.

The idea is that isn't of creating one thread per task, there is 
one thread that executes each task.

Obviously the idea is not hard but I'd like to wrap those tasks 
up in lamdas so I can instantiate them at the point I need 
them(and possibly even reuse them). I don't wanna stick all the 
code in one thread with a giant switch nor create multiple 
threads.

The main problem is that each delegate might have different 
arguments and return values associate with it and, while 
templates probably can handle it, it seems like it could be a 
mess.

Any ideas how to accomplish this effectively? The main thread 
will effectively be a task scheduler that will will be able to 
execute tasks sequentially and in parallel and interrupt with 
interval execution(probably using fibers to do so).


An easy way to think about this is for animations. We might want 
to animate several things at the same time at different rates. So 
each task will do the frame of the animation then yield. The 
scheduler does it's job and sequences everything so it all comes 
out correctly(each animation frame is rendered as soon as it is 
suppose to. If it's a 30fps second animation then the scheduler 
tries to call the task 30 times a second. If it's 1fps then it 
does so once a second... interleaving everything etc.


e.g.,

int N = 100;
scheduler.AddTask((int N) { for(int i = 0; i < N; i++) { 
displayImage("Animation", i); yeild; } }, 100, N); // Display the 
ith frame of animation at 10fps.

Or whatever.

Essentially the scheduler should do nothing until a task is 
added, schedule them as it should, etc.

Now, the hard thing, I think is that the delegates should capture 
the local context, but they are ran on a different thread so any 
local values are passed along... which requires templates since 
they might be different for each delegate: e.g.


Event e = widgetEvent;
scheduler.AddTask((Event e) { for(int i = 0; i < e.Count; i++) { 
AddEventCycles(e.Cycle[i]); yield; } }, 10, e);


and I think that is probably the hard part since we need to store 
the delegates in a heterogeneous container of delegates.

Anyways, Would be nice if something like this already existed or 
would be easy to implement.
Aug 08 2017