Multi-threaded lock test

I have a class that uses read-write lock.

I want to find out if I am locked and protected all methods correctly.
Is there a design pattern to check if the locks are set correctly?

Edit:
Some clarifications:

This is C # code derived from C ++ / CLI code that has locks at the C ++ level ... Not so simple. That's why I am looking for a design for the test, and not for the design, how to block it.

There are a few things to check for multithreading:

No dead ends (most obvious)
Correctness (if I update it in 1 thread, it will be visible in another)
Atomic write (If I write in one thread, I can only read when writing the full value)
Justice (maybe more theoretical, to prove it should be true if I use Mutex anyway)

+7
source share
2 answers

You might want to read SyncLock and SyncRoot, which are used to create a common lock pattern for your objects. Since you do not want to lock the enitre object, you often have a SyncRoot that you lock.

An example of this is an ArrayList or ICollection, which have SyncRoot, which you should use to lock the collection. You can learn more about Stream Sync on MSDN .

But overall, this is exactly the same as Mark pointed out, be careful, check, check, check and do one more test!

SyncLock Example

public class Person { public decimal Salary { get;set; } public string Name { get; set; } public readonly object SyncRoot = new object(); } 

Then you can approach the lock as follows:

 var person = new Person { Name = "Bill", Salary = 1000000 }; lock(person.SyncRoot) { IncreasSalary(); } 

A bad pattern should do lock(this) NEVER do it!

There is also somthing called Double Checking Lock , which is not related to .NET, you can also read this article on "Strategic locking, threaded interface and locking with binding" .

Thread Safety Testing

If you want to check thread safety, I recommend that you check Unit test for thread safety , the accepted answer points to Microsoft Chess , which will help you determine deadlocks in your application.

+6
source

You know the problem, this is the first step. It is (usually) NP-complete ... however there are tools:

  • Helgrind

part of valgrind toolkit; this will test the use of the most common synchronization primitives; you could talk about your own primitives.

  • Intel Parallel Inspector

Similarly, you can describe your own primitives for validation during use. See Intel Inspector reports data race in my spinlock implementation

Update I only found that GNU libstdc (++) and GNU gcc significantly improved support for Helgrind, see release notes 4.6.x and this page

It also links the following additional tools

+2
source

All Articles