Static analysis tool to check locking before access to variable Static analysis tool to check locking before access to variable multithreading multithreading

Static analysis tool to check locking before access to variable


Multithreading is hard. Using locks is not the only way to make operations thread-safe. A developer may use non-blocking synchronization with a loop and Interlocked.CompareExchange, or some other mechanism instead. A rule can not determine if something is thread-safe.

If the purpose of rules is to ensure high quality code, I think the best way to go about this is to create a thread-safe version of your class which is simple to consume. Put checks in place that the more-complex synchronization code is only modified under code review by developers that understand multithreading.


With NDepend you could write a code rule over a LINQ query (CQLinq) that could look like:

warnif count > 0 from m in Methods where m.IsUsing ("YourNamespace.YourClass.foo") && (    ! m.IsUsing ("YourNamespace.YourClass.bar") ||   ! m.IsUsing ("System.Threading.Monitor.Enter(Object)".AllowNoMatch()) ||   ! m.IsUsing ("System.Threading.Monitor.Exit(Object)".AllowNoMatch()) )select new { m, m.NbLinesOfCode }

Basically it will matches methods that uses the field foo, without using the field bar, or without calling Monitor Enter or Exit. This is not exactly what you are asking for, since you want lock explicitely on bar, but this is simple and quite close.

Notes that you can also write...

m.AssignField("YourNamespace.YourClass.foo")

... to restrict a specific write/assign field usage on foo.


One of possible solutions could be implementation of Code Contracts. You define rules, run them at compile time (so can be also integrated in your CI environment if any) and get results.

For en example of using CodeContracts like a tool for code static analys see :

Static Code Analysis and Code Contracts