Reputation: 6041
In C#, you can limit the number of threads, like this:
Parallel.For(0, 10, new ParallelOptions { MaxDegreeOfParallelism = 4 }, count =>
{
Console.WriteLine(count);
});
Does Delphi have this in latest compiler e.g. Berlin. Or does the omnithreadlibrary have this?
Upvotes: 2
Views: 1621
Reputation: 12955
this question have more implication that you think. first Tparallel is designed to work only on specifical case. for exemple
this is good to do with tparallel
TParallel.For(1, Max, procedure (I: Integer)
begin
Do_processor_intensive_work
end);
this must be avoiding :
TParallel.For(1, Max, procedure (I: Integer)
begin
do_waiting_proc_like_downloading_url
end);
why? and this is where i answer to your question : it's because Tparallel create the number of thread that match the number of processor (virtual or physical) available on the system. so if you have 32 processors then it's will create max 32 threads, if you have only 1 processor then it's will create only one thread. this is also global to all the app, if you have 2 thread that each do Tparalell, you will not have more than one thread by processor
so the idea behing Tparallel is that you don't need to worry about the number of thread, the system choose the most optimal number for you. but as you see in my sample, if your tparallel is not processor intensive, then you will probably need more thread than the number of available processor and in that case i strongly sugest to avoid tparallel and use instead TanonymousThread
you can override this number by doing SetMaxWorkerThreads (that by default is the number of processor) but if you need to do this their is great luck that you must avoid at all to use Tparallel and need to use instead TanonymousThread
Upvotes: 1
Reputation: 16065
Or does the omnithreadlibrary have this?
It does have it too.
If you would start with Parallel.For
constructor, then you obtain IOmniParallelSimpleLoop
Interface which has .NumTasks
method, defaulting to CPU cores count. It might be adjusted if you detach the loop from the current execution thread using .NoWait
call.
Whether you start with Parallel.ForEach
generator you obtain the IOmniParallelLoop
Interface and it has NumTasks
as well.
See chapters 2.12.4 and 2.11.1 at http://otl.17slon.com/book/chap04.html#highlevel-for
Also see http://www.thedelphigeek.com/2011/01/parallel-for-implementation-1-overview.html for the generic idea of the intended call syntax.
It should be something like
Parallel.ForEach(0, 10 (* ,1 *) )
.NumTasks( 4 )
.Execute(
procedure (const elem: integer)
begin
WriteLn( elem );
end
);
Upvotes: 2
Reputation: 613451
Use the Parallel.For
overload that accepts a TThreadPool
, and supply a thread pool that limits the number of threads. That is done with the SetMaxWorkerThreads
method.
Note that I obtained this information by reading the documentation.
Upvotes: 3