//---------------------------------------------------- // mgs.cc //---------------------------------------------------- #include // std::cout #include // msgget, msgsnd, msgrcv, msgctl #include // std::thread //---------------------------------------------------- using namespace std::literals; //---------------------------------------------------- const size_t N = 8; //---------------------------------------------------- class mgs_mutex { public: mgs_mutex(): id(msgget(IPC_PRIVATE, 0600)) { unlock(); } ~mgs_mutex() { msgctl(id, 0, IPC_RMID); } void lock() { msgrcv(id, &buffer, 0, 1, 0); } void unlock() { msgsnd(id, &buffer, 0, 0); } private: struct msgbuf { long mtype; char mtext[1]; }; int id; msgbuf buffer = {1, {'\0'}}; } m; //---------------------------------------------------- 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) { m.lock(); seccion_critica(); m.unlock(); } } //---------------------------------------------------- int main() { std::jthread threads[N]; for (auto &i : threads) i = std::jthread(hebra); } //----------------------------------------------------