Reputation:
Is there a way to speed up the delay when TThreadpool add new tasks after it detect low cpu?
For example, I set the MaxWorkerThreads to 100 and then MinWorkerThreads to 1, then create in a loop 100 tasks:
for j:=0 to tthreadpool.Default.MaxWorkerThreads-1 do
begin
task:=TTask.Run(procedure
var
x,i:integer;
begin
while ttask.CurrentTask.Status<>ttaskstatus.Canceled do
begin
for i:=0 to 10000 do x:=round(sin(i));
sleep(1);
end;
end);
end;
Note that the code above is just an example with some nonsense code in it, just so the task has something to do.
CPU is below 5 all the time, and it still take TThreadPool 1 second to add a new task, which means, it take a long time until finally 100 tasks are running.
Is this because it check every second how the CPU usage is before deciding to add a new task?
Is there a way to speed this up without setting the MinWorkerThreads to 100 or is it by design and I need to use TThread?
Upvotes: 1
Views: 4836
Reputation: 31
For others reading this post, I've just logged a bug with quality control. It appears like the TThreadPool (at least in the latest Delphi 10.2.3) actually never goes above the MINIMUM worker count which might be why your code isn't doing what it should. There is also an issue with SetMinWorkerThreads/SetMaxWorkerThreads values on a thread pool. If max is set to say 4 and you try and set min to 8 before adjusting max to say 10, it will not set your min value. Both issues are massive gotchas here.
Adjust System.threading.pas manually as follows and add to your project...
function TThreadPool.ShouldGrowPool: Boolean;
begin
Result := {(FWorkerThreadCount < FMinLimitWorkerThreadCount) and }(FIdleWorkerThreadCount < FQueuedRequestCount) and
(FWorkerThreadCount < Self.FMaxLimitWorkerThreadCount);
end;
Upvotes: 3