1

I have data protected by a mutex, and accessed by several threads. One runs in the background and updates (write) the data, and other threads do read operations (so they use a shared lock while the first thread uses a unique lock)

Whenever the read threads try to lock the mutex, I would like the writing one to unlock and relock for waiting the reading task completion. The writing thread is a loop, it can periodically check for this.

Is there a standard way to do this or do I need to do my own implementation based on condition variables?

And more specifically, if I own a lock on a mutex, and another thread is blocked trying to lock the mutex, do I have any guarantee that unlocking and relocking immediately will pass the lock to the waiting thread?

galinette
  • 8,896
  • 2
  • 36
  • 87
  • 2
    Perhaps you are looking for [Reader/Writer Locks in C++](https://stackoverflow.com/questions/244316/reader-writer-locks-in-c)? Your "writer lock" could periodically unlock the mutex and attempt to re-lock it. – Drew Dormann Oct 24 '22 at 13:55
  • _"do I have any guarantee that unlocking and relocking immediately will pass the lock to the waiting thread?"_ - No. The same thread may get to lock it before the waiting thread. – Ted Lyngmo Oct 24 '22 at 13:59
  • In general, dont pass mutexes around. Your datastructures and mutexes should al go into one class. Keep your locks short (local scope) and depending on the use case : std::scoped_lock/std::unique_lock or std::shared_lock to ensure your lock is always freed if you leave a scope. – Pepijn Kramer Oct 24 '22 at 14:13
  • @PepijnKramer I dont want to pass a mutex or any variable/reference to anything. I want to pass (conceptually) a mutex lock, in other words unlock the mutex in favor of a thread waiting for the lock. – galinette Oct 24 '22 at 14:23
  • Thats not how mutexes work (at least not in my mind and I've been using them a long time > 20 years). Mutexes are by default unlocked, and you lock them for short durations to do some critical work and then unlock them again. That unlocking will allow other threads to acquire the lock (which thread that is depends on the OS scheduler and may not be predictable). You can't make a mutex unlock because a new thread wants access, it is up to the thread that holds the lock to release it. That's also why it is important to keep locks for only a short time, otherwise the whole process slows down. – Pepijn Kramer Oct 24 '22 at 14:42
  • The proposed reader/writer locks are a bit more complex, it allows multiple threads "inside the lock" to read data. But they are blocked when another thread has requested write access. (Single writer, multiple readers) and that in some use cases can speed things up quite a bit. – Pepijn Kramer Oct 24 '22 at 14:44
  • I am trying to write codes like this, but I don't know how long it should sleep:`mutex.unlock; std::this_thread::sleep_for(std::chrono::milliseconds(?)); mutex.lock;` – Destiny Feb 01 '23 at 02:56

0 Answers0