A
A
AlexEternal2018-10-27 17:21:18
C++ / C#
AlexEternal, 2018-10-27 17:21:18

How to force ThreadPool to start threads correctly?

Hello. There is a task to torture C # but make it work as I need.
In general, there is a method that is called in a multithread. Here it is called 9 times.
In each thread, the timing will be different, that is, the operating time will be different.

static void Main()
        {
            ThreadPool.SetMaxThreads(3, 3);
            for (int i = 0; i < 9; i++)
                ThreadPool.QueueUserWorkItem(JobForAThread, new object[] { i });
            Console.ReadLine();
        }
static void JobForAThread(object state)
        {
            object[] array = state as object[];
            int x = Convert.ToInt32(array[0]);
            Console.WriteLine("цикл {0}, выполнение внутри потока из пула {0}", x,
                    Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(10000);
            Console.WriteLine("Закончил работать {0}", x);
        }

Exit:
5bd4733e5791b112718212.png
But this is not right for me, I need it differently. Roughly speaking, I have n -iterations and the JobForAThread method will be called. Since I specified SetMaxThreads(3,3) I expected that she would finish with three threads first and then she would start working.
That is, as a result, I need:
cycle 0, execution inside a thread from pool {0}
cycle 1, execution inside a thread from pool {1}
​​cycle 2, execution inside a thread from pool {2}
....wait until they finish
"Finished run {0}"
loop 3, run inside thread from pool {3}
"Finished running {1}"
loop 4, run inside thread from pool {4}
"Finished running {2}"
, etc.
What am I doing wrong? And ThreadPool is not suitable for this task?
UPD:
Everything is fine, the error was that the SetMaxThreads method cannot set fewer threads than the number of cores, namely:
The maximum number of worker threads or I/O completion threads in Number cannot be set less than the number of processors on the computer. To determine how many processors are present, get the value of the Environment.ProcessorCount property. Additionally, you cannot set the maximum number of worker threads or I/O completion threads to a number less than the corresponding minimum number of worker threads or I/O completion threads. To determine the minimum thread pool size, call the GetMinThreads method.

Use this information, everything works as it should:
5bd47ad86d5e5579698015.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question