0

I'm trying to optimize the following snippet:

lock()
if (!consumed) {
  consume()
  consumed = true
}
unlock()

Obviously, only the first one to come will execute the consume() function. Any later one will become no-op but in this case, they will need to lock - unlock which is unnecessary. The additional requirement is if the consumed flag is set then all threads need to wait until it is consumed, so they can not just simply skip.

what is the best way to name this problem and how to optimize it ?

w00d
  • 5,416
  • 12
  • 53
  • 85
  • You can use a `tryLock` and double-checked locking if the `consumed` flag isn't reset by a producer to signal new work to process. – Ben Manes Aug 22 '15 at 01:00
  • @Ben problem is late-coming threads need to wait for the consumption too, so they need to wait on something. – w00d Aug 22 '15 at 01:25
  • 1
    ahh, then there isn't much you can do to optimize except double-checked locking to avoid locking when complete. This is effectively a memoization pattern (lazy computation). – Ben Manes Aug 22 '15 at 02:22

0 Answers0