class mutex { private: // Mutex state variable, zero means free. int val = 0; public: void lock () { int old; // Atomically increment the state and // get the old value, which should be // zero if mutex was free. while ((old = atomic_inc (val)) != 0) { // The old value was not zero, meaning mutex was not free. // Wait unless the value has changed since the increment. futex_wait (&val, old + 1); } } void unlock () { val = 0; // Wake a waiting caller if any. futex_wake (&val, 1); } }
unlock always calls kernel which is slow
contention causes cache ping pong
contention causes counter overflow