//----------------------------------------------------- // stallings.cc: prioridad a lectores //----------------------------------------------------- #include #include #include #include #include #include #include //----------------------------------------------------- using namespace std::literals; //----------------------------------------------------- const size_t N = 24; // número de hebras //----------------------------------------------------- std::latch latch(N); std::mutex em_leyendo; // exclusión mutua leyendo size_t leyendo = 0; // nº lectores std::mutex no_escritor; // exclusion mutua latch/e //----------------------------------------------------- void seccion_critica(char c) { for (char i = 0; i < 10; ++i) std::cout << c; std::cout << '\n'; } //----------------------------------------------------- void lector(char c) { latch.arrive_and_wait(); while (true) { em_leyendo.lock(); if (++leyendo == 1) no_escritor.lock(); em_leyendo.unlock(); seccion_critica(c); em_leyendo.lock(); if (--leyendo == 0) no_escritor.unlock(); em_leyendo.unlock(); } } //----------------------------------------------------- void escritor(char c) { latch.arrive_and_wait(); while (true) { no_escritor.lock(); seccion_critica(c); no_escritor.unlock(); } } //----------------------------------------------------- int main() { for (size_t i = 0; i < N / 2; ++i) { std::thread(lector, '0' + i).detach(); std::thread(escritor, 'a' + i).detach(); } std::this_thread::sleep_for(12ms); } //-----------------------------------------------------