(C#) Lock - 将对象上锁,互斥多个线程,使同步。

C# Lock

原文:http://www.dotnetperls.com/lock

Locking is essential in threaded programs. It restricts code from being executed by more than one thread at the same time. This makes threaded programs reliable. The lockstatement uses a special syntax form to restrict concurrent access.

Keywords

Note:Lock is compiled into a lower-level implementation based on threading primitives.

Example

Here we see a static method "A" that uses the lock statement on an object. When the method A is called many times on new threads, each invocation of the method accesses the threading primitives implemented by the lock.

Then:Only one method A can call the statements protected by the lock at a single time, regardless of the thread count.

Program that uses lock statement: C#

using System;
using System.Threading;

class Program
{
    static readonly object _object = new object();

    static void A()
    {
	// Lock on the readonly object.
	// ... Inside the lock, sleep for 100 milliseconds.
	// ... This is thread serialization.
	lock (_object)
	{
	    Thread.Sleep(100);
	    Console.WriteLine(Environment.TickCount);
	}
    }

    static void Main()
    {
	// Create ten new threads.
	for (int i = 0; i < 10; i++)
	{
	    ThreadStart start = new ThreadStart(A);
	    new Thread(start).Start();
	}
    }
}

Possible output of the program

28106840
28106949
28107043
28107136
28107246
28107339
28107448
28107542
28107636
28107745

In this example, the Main method creates ten new threads, and then calls Start on each one. The method A is invoked ten times, but the tick count shows the protected method region is executed sequentially—about 100 milliseconds apart.

Note:If you remove the lock statement, the methods will be executed all at once, with no synchronization.

Intermediate representation

Let‘s examine the intermediate representation for the lock statement in the above example method A. In compiler theory, high-level source texts are translated to lower-level streams of instructions.

Tip:The lock statement here is transformed into calls to the static methods Monitor.Enter and Monitor.Exit.

Also:The lock is actually implemented with a try-finally construct. This uses the exception handling control flow.

Intermediate representation for method using lock

.method private hidebysig static void A() cil managed
{
    .maxstack 2
    .locals init (
	[0] object obj2)
    L_0000: ldsfld object Program::_object
    L_0005: dup
    L_0006: stloc.0
    L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)
    L_000c: ldc.i4.s 100
    L_000e: call void [mscorlib]System.Threading.Thread::Sleep(int32)
    L_0013: call int32 [mscorlib]System.Environment::get_TickCount()
    L_0018: call void [mscorlib]System.Console::WriteLine(int32)
    L_001d: leave.s L_0026
    L_001f: ldloc.0
    L_0020: call void [mscorlib]System.Threading.Monitor::Exit(object)
    L_0025: endfinally
    L_0026: ret
    .try L_000c to L_001f finally handler L_001f to L_0026
}

Relativity

By using the lock statement to synchronize accesses, we are creating a communication between time and state. The state is connected to the concept of time and sequential accesses to the lock.

In the Theory of Relativity, there is also a communication between time and state. This is the speed of light, which is a constant based on the relation of time and space. This connection is present also in locks—in threading constructs.

Tip:For a better description of how relativity mirrors concurrent synchronization, please see the wizard book.

Summary

We examined the lock statement in the C# language, first seeing its usage in an example program, and then describing this synchronization. Next, we stepped into the intermediate representation and its meaning in compiler theory.

Finally:We related the Theory of Relativity and the complexities of the physical universe to the lock statement.

时间: 2024-10-06 00:16:26

(C#) Lock - 将对象上锁,互斥多个线程,使同步。的相关文章

windows下多线程同步(利用事件对象,互斥对象,关键代码段)实现

一:利用事件实现线程同步 1.createthread函数的用法 hThread = CreateThread(&security_attributes, dwStackSize, ThreadProc,pParam, dwFlags, &idThread) ; HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes, DWORD dwStackSize, LPTHREAD_START_ROUTINE lpStartAdd

Linux多线程--使用互斥量同步线程【转】

本文转载自:http://blog.csdn.net/ljianhui/article/details/10875883 前文再续,书接上一回,在上一篇文章:Linux多线程——使用信号量同步线程中,我们留下了一个如何使用互斥量来进行线程同步的问题,本文将会给出互斥量的详细解说,并用一个互斥量解决上一篇文章中,要使用两个信号量才能解决的只有子线程结束了对输入的处理和统计后,主线程才能继续执行的问题. 一.什么是互斥量 互斥量是另一种用于多线程中的同步访问方法,它允许程序锁住某个对象,使得每次只能

python多线程编程(2): 使用互斥锁同步线程

上一节的例子中,每个线程互相独立,相互之间没有任何关系.现在假设这样一个例子:有一个全局的计数num,每个线程获取这个全局的计数,根据num进行一些处理,然后将num加1.很容易写出这样的代码: # encoding: UTF-8import threadingimport time class MyThread(threading.Thread): def run(self): global num time.sleep(1) num = num+1 msg = self.name+' set

递归锁+条件锁+互斥锁-04-多线程

1 // 2 // ViewController.m 3 // 05-递归锁(recursive)+条件锁(condition) 4 // 5 // Created by mac on 16/4/20. 6 // Copyright © 2016年 mac. All rights reserved. 7 // 8 /* 9 10 3). 互斥锁 11 NSLock *_lock; 12 13 3)NSLock :不能多次调用,会产生死锁 14 15 2016-04-20 16:06:44.600

java Lock interface 与synchronized使用注意--java线程(第三版)

在java中,跟着synchronized关键字的lock都会在thread离开同步块的范围时被释放掉,即使是因为异常而离开范围也是一样.所以在java中使用synchronized关键字时,异常导致不释放锁而导致死锁的现象决不会发生. Lock interace代替synchronized关键字,java是不可能会知道此明确lock的范围,如果遇到异常,此lock持有的锁不会自动释放,容易导致死锁现象.有一个简单的方法可以解决这个问题:我们可以用java的finally子句来确保lock会在完

Wpf 调用线程无法访问此对象,因为另一个线程拥有该对象,解决方案

1.Wpf 多线程修改UI示例: //启动线程修改UI,抛出异常 ThreadPool.QueueUserWorkItem((q) => { button.Content = "张三"; }, null); 解决方案:使用Dispatcher.BeginInvoke+委托方式,修改UI 将修改UI的代码封装在委托中 //启动线程处理 Thread thread1 = new Thread(UpdateBtn); thread1.IsBackground = true;//设置为后

WPF 出现&ldquo;调用线程无法访问此对象,因为另一个线程拥有该对象&rdquo;

引起这种错误多半是由于在非UI线程刷新界面,解决此问题可以使用Dispatcher this.Dispatcher.Invoke(new Action(() => { UpdateUI(string infor); }));

关于多线程并发同时使用lock时的疑问

本篇对lock的解释,主要是面向unity程序员,让其在游戏中更好的运用lock排他锁. lock:排他锁 一般使用object o = new object()来进行排他判断. 如果四个线程同时执行, 例如: Parallel.For(0, 4, (i) => { lock (o) { } }); 以上代码为一个任务在4个线程下并发,当o被线程1锁,线程234均会等待,直至o解除锁定才会向下执行. 相对unity协程阻塞的解释: yield return new WaitUntil(()=>

Java 经典问题

九种基本类型及封装类 基本类型 boolean byte char short int long double void 二进制位数 1 8(一字节) 16(2字节) 16(2字节) 32(4字节) 64(8字节) 64(8字节) -- 封装器类 Boolean Byte Character Short Integer Long Double Void switch语句后的控制表达式只能是short.char.int.long整数类型和枚举类型,不能是float,double和boolean类型