0

My multithreading program works, but doesn't print all ranges. I have 100 numbers; I divide them into 10 ranges. I want do some things on threads such as print range and continue my idea according to these ranges. But these ranges are not all the expected ranges.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Test
{
    class Program
    {
        static int numberCount = 100;
        static int numberOfThreads = 10;
        static int numberOfFinishedThread = 0;
        static void Classifier(int lowIndex, int highIndex)
        {
            Console.WriteLine("L: " + lowIndex + "\tH: " + highIndex);
            numberOfFinishedThread++;
            if (numberOfFinishedThread == numberOfThreads)
            {
                Console.Write("Done. Press any key to exit.");
                Console.ReadLine();
            }
        }
        static void Main(string[] args)
        {
            int lowIndex, highIndex;
            for (int i = 0; i < numberOfThreads; i++)
            {
                lowIndex = (numberCount / numberOfThreads) * i;
                highIndex = (numberCount / numberOfThreads) * (i + 1);
                Thread thread = new Thread(() => Classifier(lowIndex, highIndex));
                thread.Start();
            }
        }
    }
}

pic

xyres
  • 20,487
  • 3
  • 56
  • 85
  • 1
    (1) `numberOfFinishedThread++` is not an atomic operation and thus not threadsafe. (2) More related to the issue you observed: `lowIndex` and `highIndex` are captured by the lambda expression ("closed over") inside the for-loop, but declared outside the scope of for-loop body. Thus, your for-loop is not doing what you expect and the values of _lowIndex_ and _highIndex_ for each call of `Classifier` are also not what you expect (see here: https://stackoverflow.com/a/8899347/2819245) –  May 07 '19 at 20:11
  • Here another blog post that probably better illustrates what is going on there in your code with regard to lowIndex and highIndex: https://www.simplethread.com/c-closures-explained/ (the link in my 1st comment is probably not as fitting, as the explanation behind it refers to closing over for/foreach loop variables) –  May 07 '19 at 20:20
  • Possible duplicate of [Captured variable in a loop in C#](https://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp) –  May 07 '19 at 20:21

0 Answers0