I have a class like the one below:
class Program
{
static void Main(string[] args)
{
var outputWindow = new OutputWindow();
var threads = new List<Thread>();
Action action = () => outputWindow.Display(20);
for (int i = 0; i < 10; i++)
{
var thread = new Thread(() => action()) {Name = "Thread " + i};
threads.Add(thread);
}
foreach (var thread in threads)
{
thread.Start();
}
}
}
public class OutputWindow
{
public void Display(int x)
{
for (int i = 0; i < x; i++)
{
Console.WriteLine(Thread.CurrentThread.Name + " Outputcounter: " + i);
}
}
}
Question is- is this thread safe and will this lead to any race condition on the local variable i inside the display method? Will all the threads increment the value of the variable "i" as expected(which is it increments the value and does not encroch into other threads value of i)
If this is threadsafe, will it be safe to assume that any local variables declared within a method is always thread safe and shared variables are the ones which needs synchronization?
Thanks, -Mike
Each method invocation will have a separate set of local variables. However, those variables could refer to objects which other methods also use. For example:
public void AppendSomething(StringBuilder builder)
{
builder.Append("Something");
}
Here builder
is still a local variable (parameters are local variables) and each invocation of AppendSomething
will have an independent variable - but you could call the method from multiple threads using the same StringBuilder
reference, so that method is not thread-safe. (As StringBuilder
isn't thread-safe.)
See more on this question at Stackoverflow