Some thoughts about how we can make a thread safe class library

What is Thread safety?

Thread safety is making sure that shared  data (Global/static) of a program  is modified by only one thread at a time without any deadlock, starvation, race condition so that program behaves correctly when its methods are called from multiple threads.

What is thread safe class library?

A class library consists of classes with some other stuff. Each class has one or more methods which can be called form different threads concurrently. A class library is called thread safe if every class of it is tread-safe. To be a class thread-safe it has to behave correctly when its methods are called from multiple threads.

To make a class library thread safe, you have to ensure the following two things for every class:

  1. Make sure that shared data (Global/static) is not modified by more than one thread concurrently.
  2. Ensure that there is no possibility of deadlock, Inconsistency, starvation, race condition.

Implementation Strategy 1(synchronized mechanism):

To implement requirement 1, every concurrent thread has to use some synchronized mechanism like locking when they are executing critical section of code. To ensure requirement 2, you have to make the design carefully. Implementation in this way still has problem because you have to ensure that there is no possibility of deadlock, Inconsistency, starvation, race condition.

Implementation Strategy 2(TLS):

If shared data (Global/static) doesn't need to be share between threads, you can use this strategy. In this strategy you don’t need to worry about deadlock, starvation, race condition. Thread-local storage (TLS) is a concurrent  design pattern which ensures shared data (Global/static) are allocated such that there is one instance of shared data (Global/static) per thread.

Using System.Threading namespace one can use TLS to store data that is unique to each thread in multi-threaded applications. According to MSDN the common language runtime allocates a multi-slot data store array to each process when it is created. Thread’s local storage is unique per thread and one’s thread local storage is not available to other threads. Multiple threads can use same named slot (TLS) to store their data without any conflict. Use the AllocateNamedDataSlot method to allocate a named data slot. A static variable tagged with ThreadStaticAttribute is not shared between threads .Thread static members has per-thread storage rather than per AppDomain like normal static members. Thread-relative static fields provide much better performance than data slots, and enable compile-time type checking.    

No Comments