How to assert if a std::mutex is locked?

前端 未结 7 1574
难免孤独
难免孤独 2020-12-03 13:30

With GCC 4.8.2 (on Linux/Debian/Sid 64 bits) -or GCC 4.9 when available - in C++11- I have some mutex

std::mutex gmtx;

actually, it is

7条回答
  •  生来不讨喜
    2020-12-03 14:03

    std::unique_lock has owns_lock member function (equivalent of is_locked as you say).

    std::mutex gmtx;
    std::unique_lock glock(gmtx, std::defer_lock);
    
    void alpha(void) {
       std::lock_guard g(glock);
       beta(void);
       // some other work
    }
    void beta(void) {
       assert(glock.owns_lock()); // or just assert(glock);
       // some real work
    }
    

    EDIT: In this solution, all lock operations should be performed via unique_lock glock not 'raw' mutex gmtx. For example, alpha member function is rewritten with lock_guard> (or simply lock_guard).

提交回复
热议问题