//--------------------------------------------------------- // ballhausen.cc //--------------------------------------------------------- #include #include #include #include #include #include #include //--------------------------------------------------------- using namespace std; //--------------------------------------------------------- const unsigned N = 8; atomic run(true); mutex em; // exclusión mutua sem_t justicia; //--------------------------------------------------------- void seccion_critica(char c) { for (char i = 0; i < 10; ++i) cout << c; cout << endl; } //--------------------------------------------------------- void lector(char c) { while (run) { sem_wait(&justicia); seccion_critica(c); sem_post(&justicia); } } //--------------------------------------------------------- void escritor(char c) { while (run) { em.lock(); for (unsigned i = 0; i < N; ++i) sem_wait(&justicia); em.unlock(); seccion_critica(c); for (unsigned i = 0; i < N; ++i) sem_post(&justicia); } } //--------------------------------------------------------- int main() { thread lectores[N], escritores[N]; std::default_random_engine engine; sem_init(&justicia, 0, N); // N = número de lectores/escritores 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(); } //---------------------------------------------------------