CompetitionMultiple Threads attempt to obtain a lock at the same time;CompetitionThis means there are a large number of contention threads;Low CompetitionIs the opposite of the competition. In the ttaslock class, the setlock () method uses two steps: it constantly reads the lock. When the lock seems idle, it tries to get the lock. If another thread acquires a lock between Step 1 and step 2, the lock is highly likely to be used. Obviously, trying to obtain a lock with high contention is a situation that should be avoided. At this time, the chance for the thread to obtain the lock is very small, because this attempt will lead to an increase in bus traffic (resulting in traffic congestion ). On the contrary, it will be more effective if you let the thread back for a period of time to give the chance to end the competing thread.
How long should the thread retreat before retry? A good principle is that the more unsuccessful attempts, the higher the possibility of contention, and the longer the thread needs to retreat. The following is a simple method. Every time the thread finds that the lock is idle but cannot obtain it, it will be withdrawn before retry. To prevent conflicting concurrent threads from entering the lock acquisition step, that is, all threads attempt to obtain the lock at the same time point, the thread should be randomly withdrawn for a period of time. Every time a thread tries to obtain a lock but fails, it doubles the return time until a fixed maximum value of maxdelay is reached.
Code
1 Public Class Backoff
2 {
3 Private Int Mindelay, maxdelay;
4 Private Int Limit;
5 Private Random random;
6
7 Public Backoff ( Int Min, Int Max)
8 {
9 Mindelay = Min;
10 Maxdelay = Max;
11 Limit = Mindelay;
12 Random = New Random ();
13 }
14
15 Public Void Backoff ()
16 {
17 Int Delay = Random. Next (Limit );
18 Limit = Math. Min (maxdelay, 2 * Limit );
19 Thread. Sleep (Delay );
20 }
21 }
22
23 Public Class Backofflock: ilock
24 {
25 Private Const Int Waiting = 0 ;
26 Private Const Int Executing = 1 ;
27 Int State = Waiting;
28
29 Private Static Readonly Int Min_delay = 100 ;
30 Private Static Readonly Int Max_delay = 1000 ;
31
32 Public Void Setlock ()
33 {
34 Backoff = New Backoff (min_delay, max_delay );
35 While ( True )
36 {
37 While (State = Executing ){}
38 If (Interlocked. compareexchange ( Ref State, executing, waiting) = Waiting)
39 {
40 Return ;
41 }
42 Else
43 {
44 Backoff. Backoff ();
45 }
46 }
47 }
48
49 Public Void Unlock ()
50 {
51 Interlocked. Exchange ( Ref State, waiting );
52 }
53 }