0

I have a problem where I have a kind of shared/exclusive situation except that what the shared part needn't really be shared: I'll try to explain.

The exclusive part is easy: if the exclusive lock is held, noone else is allowed to progress until the owner of the exclusive lock releases it.

The (not really) shared workers should operate like this:

  • if the exclusive lock is held, or no lock: (wait for exclusive to be released, and) do "shared" work.
  • if the "shared" lock is already held or this is the second / nth "shared worker" to wait for the exclusive lock: wait for the shared lock (of the first "shared worker") to be released, but then don't do the work, but just return, because the first "shared worker" already just did the job.

Is there a name for this lock/work pattern? If there isn't a name per se, I'm interested whether this is is used at all / what I wrote makes sense.

Martin Ba
  • 37,187
  • 33
  • 183
  • 337

2 Answers2

0

If you add "done" flag on/for the work unit, and test/set that inside the exclusive lock - what would you be missing?

Gabe
  • 138
  • 4
0

I figured out that this is just an additional (normal) lock/mutex for the shared workers:

Exclusive/Master:

  • shared_mutex.lock(); // or timed_lock(timeout)
    • do master work ...
    • release exclusive lock

Workers/Shared:

  • shared_mutex.lock_shared(); // or timed_lock_shared
    • shared lock acquired
    • if (worker_mutex.try_lock()) // normal mutex
      • worker mutex now locked
      • do work
      • release / return
    • else if worker_mutex.try_lock() failed
      • another worker is already in progress
      • wait for the other worker to finish:
      • worker_mutex.lock() // or timed lock
        • worker mutex acquired, other worker finished
        • do nothing (work was just done)
        • release / return

In my case, performance of the whole thing is utterly irrelevant. The exclusive lock is held in the order of seconds and the shared work may take a few 100 msec. What this scheme is supposed to prevent is having multiple "clients" do the (essentially) same work when multiple shared "clients" have been shared waiting for the exclusive lock and that's being released -- only one "client" will then do the work, and the others will just wait for it to finish and return.

Yes, it's pretty messy, but it's a tack-on for an already messy situation.


Helpful C++ classes:

Martin Ba
  • 37,187
  • 33
  • 183
  • 337