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 = ;//a flag indicates if a thread is using the lock public void ThreadSafeMethod()
{
if (Interlocked.Exchange(ref usingLock,1) == )//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();
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 = ;//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, ) == )
return;
}
private void Leave()
{
//reset to 0 and release the lock
Interlocked.Exchange(ref usingLock,);
}
public void ThreadSafeMethod()
{
Enter();
Console.WriteLine("Thread:{0} acquired the lock", Thread.CurrentThread.ManagedThreadId);
//do some non-thread-safe work here.
Thread.Sleep();
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锁

Thread in depth 3:Synchronization的更多相关文章

  1. Thread in depth 4:Synchronous primitives

    There are some synchronization primitives in .NET used to achieve thread synchronization Monitor c# ...

  2. Thread in depth 2:Asynchronization and Task

    When we want to do a work asynchronously, creating a new thread is a good way. .NET provides two oth ...

  3. Thread in depth 1: The basic

    Every single thread has the follow elements: Execution Context:Every thread has a execution context ...

  4. 【转】Native Thread for Win32 B-Threads Synchronization(通俗易懂,非常好)

    http://www.bogotobogo.com/cplusplus/multithreading_win32B.php   Synchronization Between Threads In t ...

  5. Efficient ticket lock synchronization implementation using early wakeup in the presence of oversubscription

    A turn-oriented thread and/or process synchronization facility obtains a ticket value from a monoton ...

  6. Thread Safety in Java(java中的线程安全)

    Thread Safety in Java is a very important topic. Java provide multi-threaded environment support usi ...

  7. java命令行HPROF Profiler

    The HPROF Profiler The Heap and CPU Profiling Agent (HPROF)是JAVA2 SDK自带的一个简单的profiler代理,它通过与Java Vir ...

  8. Java Concurrency - 浅析 CyclicBarrier 的用法

    The Java concurrency API provides a synchronizing utility that allows the synchronization of two or ...

  9. Spring事务传播机制

    Spring在TransactionDefinition接口中规定了7种类型的事务传播行为,它们规定了事务方法和事务方法发生嵌套调用时事务如何进行传播,即协调已经有事务标识的方法之间的发生调用时的事务 ...

随机推荐

  1. spring boot 配置 freemarker

    1.springboot 中自带的页面渲染工具为thymeleaf 还有freemarker 这两种模板引擎 简单比较下两者不同, 1.1freemaker 优点 freemarker 不足:thym ...

  2. Neuron network

    关于神经网络你不能不知道的一切 作者|Kailash Ahirwar 编译|Sambodhi 编辑|Vincent AI前线导语:理解什么是人工智能,以及机器学习和深度学习是如何影响人工智能的,这是一 ...

  3. 【校招面试 之 剑指offer】第10-3题 矩阵覆盖问题

    题目:我们可以使用2✖️1的小矩形横着或者竖着去覆盖更大的矩形.请问用8个2✖️1的小矩形无重叠地覆盖一个2✖️8的大矩形,共有多少种方法? 分析:当放第一块时(假定从左边开始)可以横着放,也可以竖着 ...

  4. 删除排序数组中的重复数字 II · Remove Duplicates from Sorted Array II

    重复一次 [抄题]: 给定一个排序数组,在原数组中删除重复出现的数字,使得每个元素只出现一次,并且返回新的数组的长度. 不要使用额外的数组空间,必须在原地没有额外空间的条件下完成. [思维问题]: [ ...

  5. hibernate编写流程

    1.加载hibernatexml配置文件 2.创建sessionFactory 3.根据sessionFactory创建session 4.开启事务 5.持久化操作 6.提交事务 7.释放资源 其中第 ...

  6. sql优化常用命令总结

    1.显示执行计划的详细步骤 SET SHOWPLAN_ALL ON; SET SHOWPLAN_ALL OFF; 2. 显示执行语句的IO成本,时间成本 SET STATISTICS IO ON SE ...

  7. PL/Sql快速执行 insert语句的.sql文件

    当全是 insert语句的.sql文件太大时(insert 语句条数太大),直接打开执行sql文件,pl/sql会卡死. 这是可以用pl/sql的命令窗口来执行.sql文件,操作步骤如下: 1.新建命 ...

  8. TYVJ 1940 创世纪

    Description: 上帝手中有着 N 种被称作“世界元素”的东西,现在他要把它们中的一部分投放到一个新的空间中去以建造世界.每 种世界元素都可以限制另外一种世界元素,所以说上帝希望所有被投放的世 ...

  9. Laravel Tinker 使用笔记

    我们知道,Laravel Tinker 提供了命令行式的交互调试途径.使用极其方便直观. 使用: #php artisan tinker 要点: 命令要在一行上输入完成,回车执行.>>&g ...

  10. div浮停在页面最上或最下

    div{ position:fixed; bottom:0px; // top:0px; z-index:999; } bottom:0px 浮停在最下面,top:0px 浮停在最上面:z-index ...