//---------------------------------------------------- // lamport.cc //---------------------------------------------------- #include #include #include #include //---------------------------------------------------- using namespace std::literals; //---------------------------------------------------- const size_t N = 16; std::atomic start = false, stop = false; //---------------------------------------------------- class lamport { public: void lock(size_t i) { escoger[i] = true; numero[i] = *std::ranges::max_element(numero) + 1; escoger[i] = false; for (size_t j = 0; j < N; ++j) { while (escoger[j]); while (numero[j] != 0 && (numero[j] < numero[i] || (numero[j] == numero[i] && j < i))); } } void unlock(size_t i) { numero[i] = 0; } private: std::atomic escoger[N]{false}; std::atomic numero[N]{0}; } l; //---------------------------------------------------- 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(size_t i) { while (!start) std::this_thread::yield(); while (!stop) { l.lock(i); if (!stop) seccion_critica(); l.unlock(i); } } //---------------------------------------------------- int main() { std::thread threads[N]; for (size_t i = 0; i < N; ++i) threads[i] = std::thread(hebra, i); start = true; std::this_thread::sleep_for(100ms); stop = true; for (auto &t : threads) t.join(); } //----------------------------------------------------