//--------------------------------------------------------- // monitor2.cc //--------------------------------------------------------- #include #include #include #include #include //--------------------------------------------------------- using namespace std::literals; //--------------------------------------------------------- const size_t N = 8; //--------------------------------------------------------- class barrera_t { public: barrera_t(size_t l) : contador(l), limite(l) {} void esperar() { std::unique_lock lock(mutex); size_t gen = generacion; if (--contador == 0) { ++generacion; contador = limite; lock.unlock(); bloqueadas.notify_all(); } else { // bloqueadas.wait(lock, [&]{ return gen != generacion; }); while (gen == generacion) bloqueadas.wait(lock); } } private: std::mutex mutex; std::condition_variable bloqueadas; size_t contador = 0, generacion = 0, limite; } barrera(N); //--------------------------------------------------------- void hebra(size_t yo) { std::string antes = std::to_string(yo) + ": antes\n", despues = std::to_string(yo) + ": después\n"; while (true) { std::cout << antes; barrera.esperar(); std::cout << despues; } } //--------------------------------------------------------- int main() { for (size_t i = 0; i < N; ++i) std::thread(hebra, i).detach(); std::this_thread::sleep_for(1ms); } //---------------------------------------------------------