Read contention problem with an exclusive lock
Dheeraj Jha (He/Him)
Student by nature, Engineer by profession | C++ (11/14/17) | 2 x AWS | IOT | Founder @CppIndia | ISO C++ Standard Committee Member | Member of Bureau of Indian Standards (BIS)
Sometimes it is a nightmare for a C++ developer to handle multiple threads in an application. If the number of threads is in thousands, synchronization is a nightmare.
As a C++ developer, we use a mutex to synchronize and after some efforts, we succeed to so synchronize these threads with a mutex.
Now comes a performance issue. One of those I will discuss here.
Read Contention:
There is a problem with exclusive lock is read contention
If we have multiple reader threads trying to access a shared resource(let's assume Database), in case of the exclusive lock each reader thread will take a lock on resource and process and release the lock. Meanwhile, other reader threads will wait for the resource to be free to get a lock and so on.
So let's assume each reader thread is locking resource for 1 sec and we have 1000 or 10000 reader threads. You can calculate total time required to an application to complete just reading from the database.
The solution in C++:
In C++14, there is a new class introduced as shared_timed_mutex and in C++17, shared_mutex.
How to simulate this and solve:
I simulated this performance problem with 1 writer thread and 2 reader thread. And found a significant difference in total run time.
For more details, check out the link in the first comment.
How do you deal with the consumers blocking the producers when the reader load is so asymmetric and or continuous?
Student by nature, Engineer by profession | C++ (11/14/17) | 2 x AWS | IOT | Founder @CppIndia | ISO C++ Standard Committee Member | Member of Bureau of Indian Standards (BIS)
5 年check here for more details : https://www.jhadheeraj.com/post/shared_mutex