Inconsistent lock sequence¶
ID: cs/inconsistent-lock-sequenceKind: problemSecurity severity: Severity: errorPrecision: highTags: - quality - reliability - concurrency - correctness - external/cwe/cwe-662Query suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Locks held concurrently should be locked in a consistent sequence, otherwise the program can deadlock. This rule detects nestedlock statements that lock variables in a different sequence in different parts of the program.
Recommendation¶
This problem can be avoided by ensuring that nestedlock statements always lock variables in the same sequence.
Example¶
The following example shows a program running two threads, which deadlocks becausethread1 holdslock1 and is waiting to acquirelock2, whilstthread2 holdslock2 and is waiting to acquirelock1.
usingSystem;usingSystem.Threading;classDeadlock{privatereadonlyObjectlock1=newObject();privatereadonlyObjectlock2=newObject();publicvoidthread1(){lock(lock1){Console.Out.WriteLine("Thread 1 acquired lock1");Thread.Sleep(10);Console.Out.WriteLine("Thread 1 waiting on lock2");lock(lock2)// Deadlock here{}}}publicvoidthread2(){lock(lock2){Console.Out.WriteLine("Thread 2 acquired lock2");Thread.Sleep(10);Console.Out.WriteLine("Thread 2 waiting on lock1");lock(lock1)// Deadlock here{}}}}
This problem is resolved by reordering thelock variables as shown below.
usingSystem;usingSystem.Threading;classDeadlockFixed{privatereadonlyObjectlock1=newObject();privatereadonlyObjectlock2=newObject();publicvoidthread1(){lock(lock1){Console.Out.WriteLine("Thread 1 acquired lock1");Thread.Sleep(10);Console.Out.WriteLine("Thread 1 waiting on lock2");lock(lock2){}}}publicvoidthread2(){lock(lock1)// Fixed{Console.Out.WriteLine("Thread 2 acquired lock1");Thread.Sleep(10);Console.Out.WriteLine("Thread 2 waiting on lock2");lock(lock2)// Fixed{}}}}
References¶
MSDN, C# Reference:lock Statement.
The CERT Oracle Coding Standard for Java: LCK07-J. Avoid deadlock by requesting and releasing locks in the same order.
Common Weakness Enumeration:CWE-662.