Stream races, why do streams work this way?

I have two different results: sharing two lines of code (done = true with Console.Write () one)

If I set done = true, firstly, the result will be: True

Else If I put Console.WriteLine () first, the result will be: False

Why? (see carefully that the bool variable is static!)

using System;
using System.Threading;

class Program
{
    static bool done;

    static void Main(string[] args)
    {
        new Thread(test).Start();
        test();
    }

    static void test()
    {
        if (!done)
        {
            done = true;
            Console.WriteLine(done);
        }
    }
}
+5
source share
4 answers

My bet is that there Console.WriteLinewill be enough work to keep the thread busy, while the second call test()has a chance to complete.

, WriteLine done , test done , - false.

, , done = true; , , , , done, true, Console.WriteLine.

, .


, , . , , .

:

- . Windows - , ( ).

, Console.WriteLine , , , ( done),

+8

, .

/ , :

    static bool done;
    static readonly object _mylock = new object();
    static void Main()
    {
        //Application.EnableVisualStyles();
        //Application.SetCompatibleTextRenderingDefault(false);
        //Application.Run(new Form1());
        new Thread(test).Start();
        test();
        Console.ReadKey();
    }

    static void test()
    {
        lock (_mylock)
        {
            if (!done)
            {
                Console.WriteLine(done);
                done = true;
            }
        }
    }

: readonly thanks @d4wn

+4

, Console.Writeline, , done true.

, False\nFalse, Console.Writeline done = true;? , .

+1

, , . (clr..) , . , .

, : Thread Synchronization ( #)

0

All Articles