C++ mutex RAII锁的自动释放
#include <iostream> #include <thread> #include <mutex> using namespace std; // RAII 锁的自动释放 class XMutex { public: XMutex(std::mutex& mux):mux_(mux) { cout << "构造函数" << "加锁" << endl; mux.lock(); } ~XMutex(){ cout << "析构函数" << "释放锁" << endl; mux_.unlock(); } private: std::mutex& mux_; }; static mutex mux; void testMutex() { XMutex lock(mux); cout << "testMutex......" << endl; } int main(int argc,char* argv[]) { for(int i = 0;i<10;i++) { thread th(testMutex); th.detach(); } return 0; }
C++ mutex RAII锁的自动释放
最新推荐文章于 2024-04-02 15:50:16 发布