I try to accomplish 10 (for example) tasks at a time, but according to the result of the execution of the code below, I receive, instead of the 1st second, 2-3 seconds. What am I doing wrong and how to fix it, maybe there is another way?

procedure TForm1.Button3Click(Sender: TObject); var tasks: array of ITask; value: integer; i: integer; Start, Stop: integer; Elapsed: integer; begin Start := GetTickCount; // засекли начало выполнения операции Setlength(tasks, 10); value := 0; TParallel.For(0, 10 - 1, procedure(i: integer) begin tasks[i] := TTask.Create( procedure() begin Sleep(1000); TInterlocked.Add(value, 1000); end); tasks[i].Start; end); TTask.WaitForAll(tasks); Stop := GetTickCount; // засекли окончание выполнения операции ShowMessage(FloatToStr((Stop - Start) / 1000) + #10 + 'Всего: ' + value.ToString); end; 

    1 answer 1

    In order for 10 tasks to be performed simultaneously, you need to have at least 10 free cores on the processor. There is no other way.

    If you have a processor, for example, 4 cores, then for the first second only 4 tasks will be performed, and the rest will wait for the resources (free core) to be released. For the second second, 4 more, and for the third remaining 2.

    The operating system tries to allocate processor resources correctly, and when Sleep is called in the execution thread, the OS starts other threads on this kernel. While the thread is sleeping, other threads can run on this kernel, perhaps even your next tasks. By this sometimes it turns out 2 seconds, not 3.