I know TTask
and have used TTask.WaitForAll(array)
successfully, as well as TParallel.&For()
.
But now I want to do a seemingly simple thing and don't find out how:
I have an unknown number of items coming in, this can be millions or only a few, and I don't know in advance. How can I work on them in parallel (just about 4 threads or so), but without a queue? If max threads are already busy, I want to wait for the next free slot. Something like a TTask.Run()
which just doesn't come back until it really starts running.
I guess I'm just overseeing something simple...?
When I'm through, I want to wait for all remaining tasks to finish. But of course I don't want to have millions of them in an array for WaitForAll()
.
I can imagine a possible solution (but I don't like it and hope for a much easier one using TTask
or similar):
- Push the work to a
TThreadedQueue
, it would automatically let me wait if the queue is full - Start 4 threads and let them pop from that queue in a loop
I know this might be the preferred way anyway in some cases, but my situation would not profit from it (like reusing any objects, connections or so).
Pseudocode of what would be nice and clean:
MyThreadPool:= TMyThreadPool.Create(4);
while GetNextItem(out Item) do
//the following comes back when it has really been started:
MyThreadPool.Run(procedure begin Work(Item); end);
MyThreadPool.WaitFor;