intelliproject logo

Location: Desktop development - C/C++    License: The Intelliproject Open License (IPOL)

Lock Leveling

Posted by Wong Shao Voon

Use lock leveling to prevent multi-threading deadlocks

Skill: Intermediate

Posted: 17/03/2009

Views: 545

Rating: 5.00 /5

Popularity: 0.00

Sign Up to vote for this article

Introduction

This article introduces the use of lock leveling to prevent deadlocks. Lock leveling is also known as lock ordering, lock ranking and lock hierarchies. Lock leveling always acquire the locks in relative order to prevent deadlocks. Let us look at a simple deadlock example.

If Thread1 holds lock A while waiting to hold lock B and at the same time Thread2 holds lock B while waiting to hold lock A, both threads fail to get the locks they want, thus a deadlock occurs.

If we could acquire all the locks at the same time in a atomic operation as shown above, we could solve the problem. However that is not possible. One obvious way to solve this is to always take locks in relative order. One way is to encapsulate the mutex or critical section in a class and add a unique relative number as member to this class. Then lock these mutex or critical section class using a RAII lock class which will always sort the instances of mutex or critical section class before acquiring the lock, so they will always be acquired in the same order. This RAII lock class will release the locks in its destructor. The order of releasing the locks does not matter as releasing the locks does not result in a deadlock. Below is an example of the RAII lock leveling class.

This is an example on how to use this class.

References

License

This article, along with any associated source code and files, is licensed under The Intelliproject Open License (IPOL)

About the author

Wong Shao Voon

I guess I'll write here what I does in my free time, than to write an accolade of skills which I currently possess. I believe the things I does in my free time, say more about me.

When I am not working, I like to watch Japanese anime. I am also writing some movie script, hoping to see my own movie on the big screen one day.

I like to jog because it makes me feel good, having done something meaningful in the morning before the day starts.

I also writes articles for IntelliProject; I have a few ideas to write about but never get around writing because of hectic schedule.

Location: Singapore
Ocupation: Software Developer

Sign up to post message on the article message board!