//---------------------------------------------------- // ticketlock-eb.cc //---------------------------------------------------- #include #include #include #include //---------------------------------------------------- using namespace std::literals; //---------------------------------------------------- const size_t N = 32; std::latch latch(N); std::atomic stop = false; //---------------------------------------------------- class ticketlock { public: void adquirir() { unsigned my_ticket = next++; while (my_ticket != now) std::this_thread::sleep_for( std::chrono::microseconds((my_ticket - now) << 3)); } void liberar() { ++now; } private: std::atomic next = 0, now = 0; } c; //---------------------------------------------------- void seccion_critica() { std::cout << "[" << std::this_thread::get_id() << "]: "; for (size_t i = 0; i < 10; ++i) std::cout << i; std::cout << '\n'; } //---------------------------------------------------- void hebra() { latch.arrive_and_wait(); while (!stop) { c.adquirir(); if (!stop) seccion_critica(); c.liberar(); } } //---------------------------------------------------- int main() { std::jthread threads[N]; for (auto &i: threads) i = std::jthread(hebra); std::this_thread::sleep_for(75ms); stop = true; } //----------------------------------------------------