Hello. There are for example N threads, and there is a cycle

for(int i = 0; i<=100; i++) { //какие то действия } 

How to do better so that each thread does not start from 0. That is,

 1поток = 0 2поток = 1 3поток = 2 Nпоток = N 

Maybe I think the wrong way?

    4 answers 4

    The moment you spawn a thread, you can pass it a certain set of arguments. In your case, obviously, you need to pass the stream with the number N to N as a parameter.

    How this happens in C #, talking about Thread and Thread Pool, can be found here.

      There is a ready-made solution for parallelizing a For loop

        // A basic matrix multiplication. // Parallelize the outer loop to partition the source array by rows. Parallel.For(0, matARows, i => { for (int j = 0; j < matBCols; j++) { // Use a temporary to improve parallel performance. double temp = 0; for (int k = 0; k < matACols; k++) { temp += matA[i, k] * matB[k, j]; } result[i, j] = temp; } }); // Parallel.For 

      A practical guide. Writing a simple Parallel.For loop

        Maybe I think the wrong way?

        It all depends on what you want to receive. It should be remembered that the flow is a rather expensive resource of the operating system and its support requires overhead. Running simultaneously running threads is much more than the processor cores - almost certainly will be slower than just sequential execution.

        As for the initial question, a parameter can be passed to the stream creation function, which will be available in the stream function.

         Thread newThread = new Thread(Work.DoWork); newThread.Start(42); public static void DoWork(object data) { var IntVal = (int)data; } 

        details can be found in the documentation .

          I would recommend using the AsParallel method.