0

I read, in many many articles, that multiple threads will "compete" for the same resource and try to recreate it with the following code:

    static void Main(string[] args)
    {
        List<int> list = new List<int>();

        Thread t1 = new Thread(thread1);
        t1.IsBackground = true;
        t1.Start();

        Thread t2 = new Thread(thread2);
        t2.IsBackground = true;
        t2.Start();

        Thread.Sleep(3000);
        foreach(int i in list)
        {
            Console.WriteLine(i);
        }
        Console.ReadLine();

        void thread1()
        {
            for (int i = 0; i < 10000; i++)
            {
                list.Add(i);
            }
        }

        void thread2()
        {
            for (int i = 10000; i < 20000; i++)
            {
                list.Add(i);
            }
        }
    }

But the result is still very "nice and neat" in order (from 0 to 19999), what did I do wrong?

Piggy Chu
  • 41
  • 6
  • I think that thread1 is finished before thread2 starts – Tim Schmelter Dec 30 '22 at 14:04
  • @TimSchmelter You mean 10000 iterations are nothing to today's computer? Is there a way to let those 2 threads start "together"? – Piggy Chu Dec 30 '22 at 14:07
  • 1
    If you look at .net fiddle you see that you have threading issues: https://dotnetfiddle.net/YU3BB3 A lot of numbers are missing in the list. (scroll to "missing numbers") – Tim Schmelter Dec 30 '22 at 14:11
  • @TimSchmelter Oh! I see it! So I guess my computer is simply "too powerful" for the competing effect to "kick in". Thanks for your help. – Piggy Chu Dec 30 '22 at 14:18
  • 1
    `List` is not thread safe. You have to use `lock` or replace with `ConcurrentBag`. – Svyatoslav Danyliv Dec 30 '22 at 16:33
  • 1
    @SvyatoslavDanyliv the `ConcurrentBag` is a very specialized collection that is used mainly for creating object-pools. A concurrent collection that is [more suitable](https://stackoverflow.com/questions/15400133/when-to-use-blockingcollection-and-when-concurrentbag-instead-of-listt/64823123#64823123) for common multithreading scenarios is the `ConcurrentQueue`. – Theodor Zoulias Dec 30 '22 at 19:34
  • Dear SvyatoslavDanyliv & TheodorZoulias, I'm very aware of those situations, that's why I specifically wrote in my question that I want to "recreate" those "unsafe" competitions. – Piggy Chu Jan 02 '23 at 12:47

0 Answers0