C# lock关键字(C# lock keyword)

Lock定义:

lock 关键字可以用来确保代码块完成运行,而不会被其他的线程中断,它可以把一段代码定为互斥性。

互斥段在一个时间段只允许一个线程进行执行。而其他的线程必须等待。这是通过在代码块运行期间为给定对象获取互斥锁来实现的。

简单解释执行过程?

        private static object  ojb = new object();
        lock(obj)
        {

                 //锁定运行的代码段

        } 

假设线程A先执行,线程B稍微慢一点。线程A执行到lock语句,判断obj是否已申请了互斥锁,

判断依据是逐个与已存在的锁进行object.ReferenceEquals比较(此处未加证实),如果不存在,则申请一个新的互斥锁,

这时线程A进入lock里面了。

这时假设线程B启动了,而线程A还未执行完lock里面的代码。线程B执行到lock语句,检查到obj已经申请了互斥锁,于是等待;直到线程A执行完毕,释放互斥锁,线程B才能申请新的互斥锁并执行lock里面的代码。

————————

Lock定义:

The < strong > lock keyword can be used to ensure that the code block runs without being interrupted by other threads. It can make a piece of code mutually exclusive

< strong > only one thread is allowed to execute in a mutually exclusive period. Other threads must wait. This is achieved by obtaining a mutex for a given object during the run of the code block

< strong > briefly explain the execution process

        private static object  ojb = new object();
        lock(obj)
        {

                 //锁定运行的代码段

        } 

< strong > suppose thread a executes first and thread B is a little slower. Thread a executes a lock statement to determine whether obj has applied for a mutex, < / strong >

< strong > the judgment basis is to compare object.referenceequals with existing locks one by one (unconfirmed here). If they do not exist, apply for a new mutex, < / strong >

< strong > thread a enters the lock

< strong > at this time, it is assumed that thread B is started and thread a has not finished executing the code in lock. Thread B executes the lock statement, checks that obj has applied for a mutex, and waits; Thread B cannot apply for a new mutex and execute the code in lock until thread a releases the mutex