Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-threading locks test

I have a class which uses a read-write lock.

I want to see if I've locked and protected all the methods correctly.
Is there a design pattern for a test to check if the locks are set correctly ?

Edit:
Some clarifications:

It's a C# code derived from a C++/CLI Code which has locks in the C++ level... Not that simple. That's why I'm looking for a design for a test, not for a design for how to lock it.

There are a few things that need to be checks while multithreading:

No Deadlocks (Most obvious)
Correctness (If I update it in 1 thread it will be seen in the other)
Atomic write (If I write in one thread, I will able to read only when the full value is written)
Fairness (Might be more theoretical to prove, should be true if i use Mutex anyway)

like image 802
Yochai Timmer Avatar asked Apr 04 '11 08:04

Yochai Timmer


1 Answers

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

An example for this is ArrayList or ICollection which both have a SyncRoot that you should use to lock the collection. You can read more about Thread Synchronization on MSDN.

But generally it's just like Marc pointed out, be carefull, test, test, test and do some more test!

Example of SyncLock

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

You can then approach a locking like this:

var person = new Person { Name = "Bill", Salary = 1000000 };

lock(person.SyncRoot)
{
    IncreasSalary();
}

A bad pattern is to do lock(this) NEVER do that!

There is also somthing called Double-checked locking which is not specific to .NET you might also want to read this paper on "Strategized Locking, Thread-safe Interface, and Scoped Locking".

Testing for thread safety

If you want to test for thread safety I recommend you check out "Unit test for thread safety", the accepted answer points to Microsoft Chess which can help you identify deadlocks in your application.

like image 72
Filip Ekberg Avatar answered Oct 10 '22 13:10

Filip Ekberg