C++ Guidelines for Multithreaded System

Mutithreading è Parallelism è Achieve concurrency.
Below are some of the guidelines to follow for building C++ Multithreaded system.

Ø std::thread function arguments are pass by value by default.
Thread function arguments are pass by value by default. So, if you want the change to be persisted in the arguments passed in , then pass them by reference using std::ref().

Ø Protect shared data or resource using critical section.
    In a multithreaded environment if there are more than one thread sharing the resource/data then often it results in a undefined behaviour if the resource/shared data is not protected using synchronise mechanism. So, the shared resource/data must be protected with std::mutex .

Ø Release lock after critical section.
If a thread T1 acquires lock (mutex.lock()) before entering critical section and forgets to unlock(mutex.unlock()) then all the other threads will be blocked indefinitely and the program might hang because thread T1 gets hold of mutex and all the other threads are essentially waiting to acquire the lock. So, either use std::lock_guard() or std::unique_lock<std::mutex> lock() which used RAII to manage the creating and destruction object once it goes out of scope.

Ø Critical section must have only atomic operations.
When one thread is inside critical section then all other threads trying to enter the critical section are essentially blocked. So, the operations inside critical section must be atomic or as compact and small as possible.

Ø Acquire multiple locks in the same order to avoid deadlock

Ø Don’t try to acquire std::mutex lock twice

Ø Use join() to wait for background threads before terminating an application
    The program might crash if you forget to join a thread or detach before the main program terminates.
    The program will crash because at the end of the main function, when  thread T1 goes out of scope and the thread destructor is called. Inside the destructor, a check is performed to see if thread T1 is joinable. A joinable thread is a thread that has not been detached. If the thread is joinable it calls std::terminate.

Ø std::thread::join() blocks the calling thread

Comments

Popular posts from this blog

Signalling System #7(SS7) Protocol.

std::shared_ptr