Any mutex Protocol has the following problem: If the lock cannot be obtained, what should we do? There are two options for this. One solution is to let it continue to try. This lock is calledSpin lockThe repeated lock test process is calledRotating or waiting. It is reasonable to select the rotation method when the lock delay is short. However, only rotating in a multi-processor has practical significance.
Taslock
Code
1 Public Class Taslock: ilock
2 {
3 Private Const Int Waiting = 0 ;
4 Private Const Int Executing = 1 ;
5 Int State = Waiting;
6
7 Public Void Setlock ()
8 {
9 While (Interlocked. compareexchange ( Ref State, executing, waiting) = Executing)
10 {
11
12 }
13 }
14
15 Public Void Unlock ()
16 {
17 Interlocked. Exchange ( Ref State, waiting );
18 }
19 }
Ttaslock
Code
1 Public Class Ttaslock: ilock
2 {
3 Private Const Int Waiting = 0 ;
4 Private Const Int Executing = 1 ;
5 Int State = Waiting;
6
7 Public Void Setlock ()
8 {
9 While ( True )
10 {
11 While (State = Executing ){}
12 If (Interlocked. compareexchange ( Ref State, executing, waiting) = Waiting)
13 {
14 Return ;
15 }
16 }
17 }
18
19 Public Void Unlock ()
20 {
21 Interlocked. Exchange ( Ref State, waiting );
22 }
23 }
From the perspective of correctness, taslock and ttaslockAlgorithmIt is equivalent: Every algorithm ensures mutex without deadlocks. (The algorithms in the original book are JavaCode, Implemented using the atomicboolean class. Here, the code is changed to C # code, but I don't know how different it is from the original Java code intention.) but in the test, we found that ttaslock has better performance than taslock and has more stable performance. (The software test is not officially tested, but not used. Please give me some advice. Here is just my feeling of debugging n times)
The performance gap lies in the state = executing. Each processor has a cache, which is a high-speed Small-capacity memory used to store data that interest the processor. The access to memory is usually several orders of magnitude more than the access to the cache machine cycle. Therefore, the cache performance has a crucial impact on the overall performance of the multi-processor system structure. When the processor reads data from the memory address, it first checks whether the address and all its stored data are in its cache. If it is in the cache, the processor generates a cache hit and can immediately load this value. If not, a cache is missing and the data must be searched in the cache of the memory or another processor. Then, the processor broadcasts the address on the bus, and Other Processors listen to the bus. If a processor finds this address in its own cache, it broadcasts the address and its value to respond. If this address is not found in all processors, the system responds with the value corresponding to this address in memory.