//---------------------------------------------------- // tas.cc //---------------------------------------------------- #include #include #include //---------------------------------------------------- using namespace std::literals; //---------------------------------------------------- const size_t N = 16; std::atomic start = false, stop = false; //---------------------------------------------------- template T test_and_set(volatile T *spinlock) { T ret = true; __asm__ __volatile__("xchg %0, %1" : "+r"(ret), "+m"(*spinlock)); return ret; } //---------------------------------------------------- class cerrojo { public: void adquirir() { while (test_and_set(&cerrado)); } void liberar() { cerrado = false; } private: volatile bool cerrado = false; } 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(); } //----------------------------------------------------