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