当前位置:网站首页>Why use lock [readonly] object? Why not lock (this)?
Why use lock [readonly] object? Why not lock (this)?
2022-06-24 07:02:00 【Machine vision 001】
1. Why use lock?lock What happened ?
When we use threads , The most efficient way, of course, is asynchronous , That is, each thread runs at the same time , There is no interdependence and waiting .
But when different threads need to access a resource , We need a synchronization mechanism .
That is to say, when reading and writing the same resource , We want to make this resource be operated by only one thread at a time , To ensure that each operation is effective and immediate , That is, to ensure the atomicity of its operation .
lock yes C# The most commonly used synchronization method in , The format is lock(objectA){codeB} .
lock(objectA){codeB} It seems simple , Actually, it has three meanings , This is critical to the proper use of it :
1. objectA By lock Did you? ? No, , I'll do it lock, Otherwise, we will wait , until objectA Be released .
2. lock In the future codeB Other threads cannot call during codeB, Can't be used objectA.
3. After execution codeB After the release of objectA, also codeB Can be accessed by other threads .
2. lock(this) What's up? ?
using System;
using System.Threading;
namespace Namespace1
{
class C1
{
private bool deadlocked= true;
// This method uses lock, We hope lock Can only be accessed by one thread at a time
public void LockMe(object o)
{
lock (this)
{
while(deadlocked)
{
deadlocked = (bool)o;
Console.WriteLine("Foo: I am locked :(");
Thread.Sleep(500);
}
}
}
// Methods that all threads can access at the same time
public void DoNotLockMe()
{
Console.WriteLine("I am not locked :)");
}
}
class Program
{
static void Main(string[] args)
{
C1 c1 = new C1();
// stay t1 Call in thread LockMe, And will deadlock Set to true( There will be a deadlock )
Thread t1= new Thread(c1.LockMe);
t1.Start(true);
Thread.Sleep(100);
// In the main thread lock c1
lock (c1)
{
// The call was not lock Methods
c1.DoNotLockMe();
// Called by lock Methods , And try to put deadlock relieve
c1.LockMe(false);
}
}
}
}stay t1 In the thread ,LockMe Called lock(this), That is to say Main Function c1, At this time, the main thread calls lock(c1) when , You have to wait t1 Medium lock The block cannot be accessed until it has been executed c1, That is all c1 Related operations cannot be completed , So we saw Lian c1.DoNotLockMe() No execution .
hold C1 The code of is slightly changed :
class C1
{
private bool deadlocked= true;
private object locker= new object();
// This method uses lock, We hope lock Can only be accessed by one thread at a time
publicvoid LockMe(object o)
{
lock (locker)
{
while(deadlocked)
{
deadlocked = (bool)o;
Console.WriteLine("Foo: I am locked :(");
Thread.Sleep(500);
}
}
}
// Methods that all threads can access at the same time
publicvoid DoNotLockMe()
{
Console.WriteLine("I am not locked :)");
}
}This time we use a private member as the lock variable (locker), stay LockMe Only the private is locked in locker, Not the whole thing . Then run the program again , You can see that although t1 There's a deadlock ,DoNotLockMe() It can still be accessed by the main thread .LockMe() Still not accessible , The reason is that it is locked locker Not yet. t1 Release .
Key points :
1. lock(this) The disadvantage of is that after a thread locks an object, the entire object cannot be accessed by other threads .
2. Locking is not just about lock Code in segment , The lock itself is thread safe .
3. We should use private objects that do not affect other operations as locker.
4. In the use of lock When , By lock The object of (locker) Must be of reference type , If it's a value type , Will result in every lock The object will be boxed into a new reference object ( In fact, if you use a value type ,C# compiler (3.5.30729.1) An error is given at compile time ).
remarks :
about Monitor, Find its static methods Enter(object obj) There is an exception type ArgumentNullException, perform lock(null object ) It's about , Throw an unhandled exception :System.ArgumentNullException: Value cannot be empty !
Modify the locked object in the code snippet , There will be blance<0 The situation of , And will throw an exception .
private static readonly object obj = new object();
Why set it to read-only ? This is because if lock Changes in the code snippet obj Value , The other threads are free . Because the object of the mutex has changed ,object.ReferenceEquals Must return to false. So change the above to private static readonly.
边栏推荐
- 雲監控系統 HertzBeat v1.1.0 發布,一條命令開啟監控之旅!
- Programmers use personalized Wallpapers
- SAP实施项目上的内部顾问与外部顾问,相互为难还是相互成就?【英文版】
- Nine unique skills of Huawei cloud low latency Technology
- 如何低成本构建一个APP
- 35 year old crisis? It has become a synonym for programmers
- Why does the remote end receive a check-out notice when the TRTC applet turns off audio and video locally
- System design: partition or data partition
- .NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)
- Spark参数调优实践
猜你喜欢

About Stacked Generalization

虚拟文件系统

RealNetworks vs. 微软:早期流媒体行业之争

Spark项目打包优化实践

MAUI使用Masa blazor组件库

Nine unique skills of Huawei cloud low latency Technology

程序员使用个性壁纸

Record -- about the method of adding report control to virtual studio2017 -- reportview control

基于三维GIS系统的智慧水库管理应用
![Command ‘[‘where‘, ‘cl‘]‘ returned non-zero exit status 1.](/img/2c/d04f5dfbacb62de9cf673359791aa9.png)
Command ‘[‘where‘, ‘cl‘]‘ returned non-zero exit status 1.
随机推荐
SAP实施项目上的内部顾问与外部顾问,相互为难还是相互成就?【英文版】
What is the OSI seven layer model? What is the role of each layer?
If you want to learn programming well, don't recite the code!
Are internal consultants and external consultants in SAP implementation projects difficult or successful? [English version]
华为云低时延技术的九大绝招
Kubernets traifik proxy WS WSS application
Arduino融资3200万美元,进军企业市场
程序员使用个性壁纸
leetcode:1856. 子数组最小乘积的最大值
Command ‘[‘where‘, ‘cl‘]‘ returned non-zero exit status 1.
Cloud native high availability and Disaster Recovery Series (I): pod break up scheduling
What is domain name resolution? What if the domain name cannot be resolved?
Do you know about Statistics?
leetcode:84. 柱状图中最大的矩形
Surveying and mapping principle of GIS coordinate system: geoid / datum / reference ellipsoid /epsg/sri/wkt
Let's talk about BOM and DOM (5): dom of all large Rovers and the pits in BOM compatibility
展锐芯片之GPU频率
Typora charges? Build vs Code markdown writing environment
You have a chance, here is a stage
Station B collapsed. Let's talk to the injured programmers