Reputation: 385
If you have the following problem to solve, how would you do it?
The goal is to create an array of 1000 integer values, initialized to 0 and then increment all the values using 2 threads, each thread will increment each array value by 1.
I did it with the following code but I'm really not sure my solution is ok...
static async Task Main(string[] args)
{
var count = 100;
int[] array = new int[count];
Array.Clear(array, 0, array.Length);
await Task.WhenAll(IncrementArray(array, "Task 1"), IncrementArray(array, "Task 2"));
Array.ForEach(array, Console.WriteLine);
}
static object obj = new object();
static async Task IncrementArray(int[] array, string taskName)
{
for (var i = 0; i < array.Length; i++)
{
Console.WriteLine(taskName);
await Task.Delay(100);
lock (obj)
{
array[i]++;
}
}
}
Thanks for your help!
Upvotes: 0
Views: 446
Reputation: 3607
You should use Interlocked.Increment
that is like ++
but atomic to increse the value in one unit, keeping it thread safe
Upvotes: 0
Reputation: 5042
Your solution is not OK. You have a race condition, i.e. the two threads may try to increment one element simultaneously and then produce incorrect results - an element of the array may remain 1, for example.
See Interlocked class, and also lock keyword.
Upvotes: 1