开发者

Multi-threading locks test

开发者 https://www.devze.com 2023-02-22 09:05 出处:网络
I have a class which uses a read-write lock. I want to see if I\'ve locked and protected all the methods correctly.

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)


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.


You know the problem, that's step one. It is (usually) NP-complete... however there are tools:

  • helgrind

part of the valgrind toolkit; this will be able to verify the use of the most common synchronisation primitives; you might be able to tell it about your own primitives.

  • Intel Parallel Inspector

Similarly let's you describe your own primitives for validation during use. See Intel Inspector reports a data race in my spinlock implementation

Update I just found that GNU libstdc(++) and GNU gcc have improved their support of Helgrind substantially, refer to the 4.6.x release notes and this page

It also links the following additional tools

  • Data Race Detection
  • ThreadSanitizer
0

精彩评论

暂无评论...
验证码 换一张
取 消