0

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!

13
  • 3
    I think this is a good example of what multithreading is not made for Commented Nov 13, 2019 at 10:57
  • 2
    The way data parallelism typically works is to partition the array and have each thread work with its own partition. If you used Parallel.ForEach to do the job, that's what the method would do Commented Nov 13, 2019 at 10:59
  • 2
    That's not even running the code in parallel. Each call to IncrementArray() is synchronous. Commented Nov 13, 2019 at 11:04
  • 1
    As @Matthew says, this code isn't running asynchronously. If you put an await Task.Delay(1); inside the IncrementArray method and made it async, you would then start to see errors as ++ is not thread safe. Commented Nov 13, 2019 at 11:28
  • 1
    @PlaTyPuS you don't need lock if you use Interlocked.Increment(ref array[i]) Commented Nov 13, 2019 at 12:06

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What would you suggest OP locks on though?
In his particular case, I would suggest to use Interlocked. However, I prefer to have him do some research first, before jumping to the solution. Or he will not understand why.
0

You should use Interlocked.Increment that is like ++ but atomic to increse the value in one unit, keeping it thread safe

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.