//---------------------------------------------------- // ticketlock.cc //---------------------------------------------------- #include #include #include //---------------------------------------------------- using namespace std::literals; //---------------------------------------------------- const size_t N = 8; //---------------------------------------------------- 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 << std::endl; } //---------------------------------------------------- void hebra() { while (true) { c.adquirir(); seccion_critica(); c.liberar(); } } //---------------------------------------------------- int main() { std::jthread threads[N]; for (auto &i : threads) i = std::jthread(hebra); } //----------------------------------------------------