Q1. I saw recommendations for using unique_lock and shared_lock at http://en.cppreference.com/w/cpp/thread/shared_mutex/lock , but I don’t understand why, since shared_mutex already supports lock and lock_shared methods?
Perhaps because unique_lock has existed since C ++ 11, but shared_lock comes on board with C ++ 17. In addition, [maybe] unique_lock can be more efficient. Here's the original rationale for shared_lock [by the creator] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html , and I rely on that.
Q2. Can this code cause hunger? If so, how can I avoid starvation?
Yes, absolutely. If you do:
while (1) writeFn1();
You can get the time string:
T1: writeLock.lock() T2: writeLock.unlock() T3: writeLock.lock() T4: writeLock.unlock() T5: writeLock.lock() T6: writeLock.unlock() ...
The difference T2-T1 arbitrary, based on the amount of work performed. But T3-T2 is close to zero. This is a window for another thread to get a lock. Since the window is so small, it probably won’t get it.
To solve this problem, the easiest way is to insert a little dream (like nanosleep ) between T2 and T3 . You can do this by adding it to the end of writeFn1 .
Other methods may include creating a queue for locking. If the thread cannot get the lock, it adds itself to the queue, and the first thread in the queue gets the lock when the lock is released. In the linux kernel, this is implemented for "queued spinlock"
Q3. Is there any other lock class that I can try to implement write write lock?
While not a class, you can use pthread_mutex_lock and pthread_mutex_unlock . They implement recursive locks. You can add your own code to implement the boost::scoped_lock . Your class can control semantics.
Or, boost has its own locks.