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

前端 未结 7 1557
难免孤独
难免孤独 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 13:52

    It's not technically an assertion, but I've used a similar approach to prevent unlocked access to shared state: add a reference parameter to the lock guard class on the in the unsafe function (beta in your example). Then the function cannot be called unless the caller has created a lock guard. It solves the problem of accidentally calling the function outside of the lock, and it does so at compile time with no races.

    So, using your example:

    typedef std::lock_guard LockGuard;
    void alpha(void) {
       LockGuard g(gmtx);
       beta(g);
       // some other work
    }
    
    void beta(LockGuard&) {
       // some real work
    }
    
    void gamma(void) {
       LockGuard g(gmtx);
       beta(g);
       // some other work
    }
    
    //works recursively too
    void delta(LockGuard& g)
    {
       beta(g);
    }
    

    Drawbacks:

    • Does not validate that the lock actually wraps the correct mutex.
    • Requires the dummy parameter. In practice, I usually keep such unsafe functions private so this is not an issue.

提交回复
热议问题