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 ?