//---------------------------------------------------- // mq.cc //---------------------------------------------------- #include // std::cout #include // mq_open, mq_close, mq_recv, mq_send #include // std::random_device #include // std::string, std::to_string #include // std::thread //---------------------------------------------------- using namespace std::literals; //---------------------------------------------------- const size_t N = 8; //---------------------------------------------------- class mq_mutex { public: mq_mutex(): path("/mq" + std::to_string(std::random_device{}())) { mq_attr attr = {.mq_maxmsg = 1, .mq_msgsize = sizeof(buffer)}; mq_unlink(path.c_str()); id = mq_open(path.c_str(), O_CREAT | O_RDWR, 0600, &attr); unlock(); } ~mq_mutex() { mq_close(id); mq_unlink(path.c_str()); } void lock() { mq_receive(id, &buffer, 1, NULL); } void unlock() { mq_send(id, &buffer, 1, 0); } private: std::string path; mqd_t id; char buffer; } 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); } //----------------------------------------------------