Lock-depth understanding of

Use lock 1. Under what circumstances, in the end what lock the 
first lock is not a recommended thing. Because of low performance. But if you encounter multiple threads need to use the same resources, if these resources are not changed, then there is no need to use the lock.
Only when it comes to multi-threaded with a change of public resources, it was needed. Just read is not necessary to lock.
lock What?
lock (objectA) {codeB} appears to be simple, in fact, there are three meanings, that it is essential for proper use:
1. ObjectA is lock yet? I did not come by the lock, otherwise wait until objectA is released.
2. lock after codeB during execution of other threads can not call codeB, can not be used objectA.
3. Release objectA After performing codeB, and codeB can be accessed by other threads.


the using
the System; the using the System.Collections.Generic; the using the System.IO; the using the System.Linq; the using the System.Net; the using the System.Text; the using the System.Threading; the using System.Threading.Tasks; the using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; using SevenZip; using zlib; namespace ConsoleApp1 { public class lockDemo { public object o = new object(); static Dictionary<string, string> dic = new Dictionary<string, string>(); public void NonCriticalSection(object aa) { lock (o) { dic["1"] = aa.ToString(); Thread.Sleep(1000); } } public void Consoles() { lock (dic) { for (int i=1;i<20;i++) { Thread.Sleep(500); System.Console.WriteLine("Consoles" + dic["1"]); } } } public static void Main(string[] args) { lockDemo e = new lockDemo(); Thread nt1 = new Thread(new ParameterizedThreadStart(e.NonCriticalSection)); nt1.Start("aa"); Thread nt2 = new Thread(new ParameterizedThreadStart(e.NonCriticalSection)); nt2.Start("bb"); Thread nt4 = new Thread(new ParameterizedThreadStart(e.NonCriticalSection)); nt4.Start("cc"); Thread nt3 = new Thread(e.Consoles); nt3.Start(); Console.ReadLine(); } } }


 

Guess you like

Origin www.cnblogs.com/xuedognqing/p/12124507.html