//---------------------------------------------------- // flag3.cc: versiĆ³n ttas y con uso de bloqueo de flag.cc //---------------------------------------------------- #include #include #include //---------------------------------------------------- using namespace std::literals; //---------------------------------------------------- const size_t N = 16; std::atomic start = false, stop = false; //---------------------------------------------------- class cerrojo { public: void adquirir() { while (cerrado.test(std::memory_order_relaxed) || cerrado.test_and_set(std::memory_order_acq_rel)) cerrado.wait(true); } void liberar() { cerrado.clear(std::memory_order_release); cerrado.notify_one(); } private: std::atomic_flag cerrado; } c; //---------------------------------------------------- void seccion_critica() { std::cout << "[" << std::this_thread::get_id() << "]: "; for (size_t i = 0; i < 10; ++i) std::cout << i; std::cout << std::endl; } //---------------------------------------------------- void hebra() { while (!start) std::this_thread::yield(); while (!stop) { c.adquirir(); if (!stop) seccion_critica(); c.liberar(); } } //---------------------------------------------------- int main() { std::thread threads[N]; for (auto &t : threads) t = std::thread(hebra); start = true; std::this_thread::sleep_for(100ms); stop = true; for (auto &t : threads) t.join(); } //----------------------------------------------------