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