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锁

 

转载于:https://www.cnblogs.com/lwhkdash/p/6778361.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值