
Howard Hinnant wrote:
Oops, that should be:
vs this:
void do_sale(rw_mutex& m) { read_lock rl(m);
long balance = get_balance(); long cost = get_total_cost();
if (balance > cost) { rl.unlock(m); write_lock wl(m); cost = get_total_cost(); set_balance(get_balance() - cost); wl.transfer_to_read_lock(rl); balance = get_balance(); } // ... }
but still looks much simpler, and smaller code size to me.
The read lock is pointless in this case. The idea is that get_balance() is slow, so we want to perform it under only a read lock, to avoid stalling readers unnecessarily. However your code performs it again under the write lock anyway. It's much simpler to just do the whole operation under a write lock. These examples are mostly what led me to believe that promotion isn't very useful. But I may be missing an important use case. Demotion, on the other hand, seems useful: int deposit( int amount ) // requires: amount > 0 // returns: new balance (atomic) { write_lock wr( m ); v.push_back( amount ); read_lock rd( wr ); int r = 0; accumulate( v.begin(), v.end(), r ); return r; }