Thread in depth 3:Synchronization

 Synchronization means multi threads access the same resource (data, variable ,etc) should not cause a corruption to it.If all methods of a class promise threading synchronization,we call that the class is "Thread Safe".

Thread Safety

ALL static methods of the .net framework are promised thread-safe. When we are writting class and method we should pay a little bit attention on the thread safety,we can:

  1. Avoid to use static data.Different thread can access the same static data at the same time so may cause corruption to it. 
  2. Avoid to use global variable,Use local variable.Different thread can access the same data referred by global variable. local variable inside the method will have a particular copy in the thread stack so corruption won't happen.
  3. Use lock construct. But this will cause a performance problem,because the thread will be blocked or being "spin-locked" and waste CPU and memory, so use it very carefully.

Interlocked

In most computer,read and write operation to a data is not atomically. By "atomically" it means those data will be read or written at an automical state.For example,CPU needs instructions to set a int variable from 0 to 1:

 

  1. Load a value from an instance variable into a register, by using the "MOV" instruction
  2. Increment or decrement the value,by using "INC" instruction 
  3. Store the value in the instance variable,by using "MOV" instruction

 

When a thread is doing the second step and not yet store the value back, another thread may preempt and get the origin value,a very bad problem may happen.

We can use Interlocked class which locates in System.Threading namespace to avoid this situation. Interlocked provides atomic operations for variables that are shared by multiple threads.Think of the code snippet below.

        static void Main(string[] args)
        {
            InterlockedExampleClass example = new InterlockedExampleClass();
            Task.Run(() => example.ThreadSafeMethod());
            Task.Run(() => example.ThreadSafeMethod());
            Console.Read();
        }
    }


    class InterlockedExampleClass
    {
        int usingLock = 0;//a flag indicates if a thread is using the lock

        public void ThreadSafeMethod()
        {
            if (Interlocked.Exchange(ref usingLock,1) == 0)//when an thread change the value of usingLock to 1, another thread will get a false because usingLock would be 1 then no opportunity to enter the code block.
            {
                Console.WriteLine("Thread:{0} acquired the lock", Thread.CurrentThread.ManagedThreadId);
                //do some non-thread-safe work here.
                Thread.Sleep(3000);
                Interlocked.Exchange(ref usingLock,0);//reset to 0 and release the lock
            }
        }
    }

 

 SpinLock

In the last section, we talked about the Interlocked class and show some code of how to implement a lock.But the problem is, the second thread won't wait but just skip away,but in most time we want it to wait for the first thread to be finished.We can change the code to a SpinLock.SpinLock means we keep the thread running and waitting until the first thread is finished.The change is pretty simple as you can see below:

 

    class Program
    {
        static void Main(string[] args)
        {
            InterlocedExampleClass example = new InterlocedExampleClass();
            Task.Run(() => example.ThreadSafeMethod());
            Task.Run(() => example.ThreadSafeMethod());
            Console.Read();
        }
    }


    class InterlocedExampleClass
    {
        int usingLock = 0;//a flag indicates if a thread 

        private void Enter()
        {
            //if usingLock is changed from 0 to 1,then return from this method can continue its job,otherwise keep spinning here.
            while (true)
                if(Interlocked.Exchange(ref usingLock, 1) == 0)
                return;
        }
        private void Leave()
        {
            //reset to 0 and release the lock
            Interlocked.Exchange(ref usingLock,0);
        }
        public void ThreadSafeMethod()
        {
            Enter();
            Console.WriteLine("Thread:{0} acquired the lock", Thread.CurrentThread.ManagedThreadId);
            //do some non-thread-safe work here.
            Thread.Sleep(3000);
            Leave();

        }
    }

We created the Enter method and Leave method. The first thread arrive the Enter method and set usingLock to 1 and get the origin value 0 and return,others threads have to keep dead loop until the first thread change usingLock variable back to 0.

Spinlock is not a good thing because it causes a waste lots of CPU and memory when dead looping.

See also:

Interloced Class

线程漫谈——线程同步之原子访问

线程漫谈——.NET线程同步之Interlocked和ReadWrite锁

 

posted on 2017-04-28 09:39  wyman25  阅读(310)  评论(0编辑  收藏  举报

导航