0

I'm learning about multi threading, however I can't figure out how can I achieve thread-safe in my study scenario.

This is a pseudo code, so I have a class that do some calculations and share some public data (the Formulas list), and have a public property Id to read further:

class Problem{
  public int Id {get; set;}
  public IList<Calc> Formulas {get; private set;}

  public Problem(int id){
    Id = id;
    Formulas = new List<Formulas>();
  }

  public void SolveProblem(){
    Calc newCalc = DoSomeCalculations();
    Formulas.Add(newCalc);
  }

  private Calc DoSomeCalculations(){
    var originalFormulas = Formulas.Where(x => x.Number > 2);
    return new Calc(originalFormulas);
  }
}

And I did a class to runs a lot of calculations by many threads:

class ProblemsRunner{
  public void Run(List<Problem> problemsToSolve){
    var thread1 = new Thread(RunProblem(problemsToSolve.Take(10)));
    var thread2 = new Thread(RunProblem(problemsToSolve.Skip(10).Take(10)));
    var thread3 = new Thread(RunProblem(problemsToSolve.Skip(20).Take(10)));

    thread1.Start();
    thread2.Start();
    thread3.Start();
  }

  private void RunProblem(IEnumerable<Problem> problems){
    foreach(var problem in problems){
      problem.SolveProblem();
    }
  }
}

I don't to know what is my concern in my code:

  • Is the data that class Problem shares (Formulas list, and property Id), and I just need to lock its access?

  • Do I need to worry in ProblemsRunner, and lock the entire object inside ProblemsRunner.RunProblem() foreach loop?

Because after calculations, I need to know both Id and Formulas of each object, and I can't figure out how I do this with multithreading.

You don't need to correct all the code (but feel free), I'm asking for some directions to solve this problem, and achieve thread-safety...with states and mutable objects inside a class correclty

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Wagner Leonardi
  • 4,226
  • 2
  • 35
  • 41

1 Answers1

3

Your code doesn't seem to have any of the problems you're worried about. Each problem has its own Formulas, so when you add a new formula after solving the problem, you're not accessing anything that might get accessed from another thread.

I suspect that that isn't what you intended, though. You probably wanted a single Formulas; in that case you certainly would want a thread-safe list.

You ought to use some sort of thread-safe blocking queue to manage the problems to be solved, and have each thread take another one from the queue when it's completed the current one. The problem with your current approach of sending 10 to each thread is that if the first 10 get solved more quickly than the next 10, your first thread will sit around idle. If you allocate dynamically when threads are free, you'll have all threads busy all the time (except at the very end).

chiastic-security
  • 20,430
  • 4
  • 39
  • 67