Is it safe to use a boolean flag to stop a thread from running in C#

前端 未结 4 2005
面向向阳花
面向向阳花 2020-11-29 06:27

My main concern is with the boolean flag... is it safe to use it without any synchronization? I\'ve read in several places that it\'s atomic (including the documentation).

相关标签:
4条回答
  • 2020-11-29 06:47

    BTW, I just noticed this part of the code:

    // A method which runs in a thread
        public void Run()
        {
            startSignal.WaitOne();
            while(running)
            {
                startSignal.WaitOne();
                //... some code
            }
            latch.Signal();
        }
    

    You will need to unblock the worker thread twice using "startSignal.Set()" for the code within the while block to execute.

    Is this deliberate?

    0 讨论(0)
  • 2020-11-29 06:50

    Booleans are atomic in C#, however, if you want to modify it in one thread and read it in another, you will need to mark it volatile at the very least,. Otherwise the reading thread may only actually read it once into a register.

    0 讨论(0)
  • 2020-11-29 06:54

    Booleans are atomic in C#: http://msdn.microsoft.com/en-us/library/aa691278(VS.71).aspx

    0 讨论(0)
  • 2020-11-29 07:10

    You better mark it volatile though:

    The volatile keyword indicates that a field might be modified by multiple concurrently executing threads. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

    But I would change your loop:

        startSignal.WaitOne();
        while(running)
        {
            //... some code
            startSignal.WaitOne();
        }
    

    As it is in your post the 'some code' might execute when the thread is stopped (ie. when Stop is called) which is unexpected and may be even incorrect.

    0 讨论(0)
提交回复
热议问题