//--------------------------------------------------------- // shared_lock-s.cc: share_mutex + exponential backoff //--------------------------------------------------------- #include #include #include #include #include #include //--------------------------------------------------------- using namespace std; //--------------------------------------------------------- atomic run(true); shared_mutex em; // exclusión mutua //--------------------------------------------------------- void seccion_critica(char c) { for (char i = 0; i < 10; ++i) cout << c; cout << endl; } //--------------------------------------------------------- void lector(char c) { while (run) { auto espera = 16us; while (!em.try_lock_shared()) this_thread::sleep_for(espera *= 2); seccion_critica(c); em.unlock_shared(); } } //--------------------------------------------------------- void escritor(char c) { while (run) { auto espera = 16us; while (!em.try_lock()) this_thread::sleep_for(espera *= 2); seccion_critica(c); em.unlock(); } } //--------------------------------------------------------- int main() { const unsigned N = 8; thread lectores[N], escritores[N]; std::default_random_engine engine; for (unsigned i = 0; i < N; ++i) if (engine() & 1) { lectores[i] = thread( lector, '0' + i); escritores[i] = thread(escritor, 'a' + i); } else { escritores[i] = thread(escritor, 'a' + i); lectores[i] = thread( lector, '0' + i); } this_thread::sleep_for(100ms); run = false; for(thread& i: lectores) i.join(); for(thread& i: escritores) i.join(); } //---------------------------------------------------------