//--------------------------------------------------------- // mutex-a.cc: fixing mutex.cc problem with atomic (redundant) //--------------------------------------------------------- #include #include #include #include #include //--------------------------------------------------------- using namespace std::literals; //--------------------------------------------------------- const size_t N = 2; //--------------------------------------------------------- class barrera_t { public: barrera_t(size_t l) : limite(l) {} void esperar() { size_t local = uso; m.lock(); ++en_espera[local]; m.unlock(); if (en_espera[local] != limite) { while (en_espera[local] != 0); } else { uso ^= 1; en_espera[local] = 0; } } private: std::mutex m; std::atomic en_espera[2] = {0, 0}; size_t uso = 0, limite; } barrera(N); //--------------------------------------------------------- void hebra(size_t yo) { std::string antes = std::to_string(yo) + ": antes\n", despues = std::to_string(yo) + ": después\n"; while (true) { std::cout << antes; barrera.esperar(); std::cout << despues; } } //--------------------------------------------------------- int main() { for (size_t i = 0; i < N; ++i) std::thread(hebra, i).detach(); std::this_thread::sleep_for(10ms); } //---------------------------------------------------------