In modern program development, the synchronization of resources is a relatively important topic, in. NET, there is a very rich class library for us to use, now summed up in various cases of the mechanism of resource synchronization.
1. Declare the field as volatile
When a field is declared as volatile, some of the internal mechanisms of the management Code and memory in the CLR are responsible for synchronizing the fields and always guaranteeing that the field information being read is the most recent value, and the field declared as volatile must have one of the following characteristics
1. For reference type
2. A pointer (in unsafe code)
3.sbyte,byte,short,ushort,int,uint,char,float,bool
4. An enumeration type that uses the underlying type
2. Using the System.Threading.Interlocked class
In many of the operations of an increased number of integers, it is easy to ignore threading problems, such as executing the following code
i = i + 1;
In fact, the above code is divided into 3 steps
1). Read the value of I from memory
2). Add the Read value to 1
3. Write a new value into memory
On a single thread, this operation will not have any problems, but when I was accessed by multiple threads, the problem arose, and the thread that modified the I could be interrupted by other read threads in any of the above, imagining that when the action thread finishes the second step and prepares to write the new value into memory, At this point the other read threads get execution power, at which point the value of I read is not what we want, therefore, this operation is not atomic, in. NET, using the Interlocked class can ensure the atomic nature of the operation, interlocked class has the following methods
Increment
Decrement
Exchange
The parameters of the above method are all parameters with ref, so we say that these methods guarantee the atomicity of the data, and in multiple threads, the atomic nature of the data is worth considering when it comes to the operation of integers, and the interlocked operation code is as follows
int i = 0;
System.Threading.Interlocked.Increment(ref i);
Console.WriteLine(i);
System.Threading.Interlocked.Decrement(ref i);
Console.WriteLine(i);
System.Threading.Interlocked.Exchange(ref i, 100);
Console.WriteLine(i);
The output information is as follows