简体   繁体   中英

Custom conditional scoped mutex lock

I am making a custom Conditional Scoped Mutex Lock.

I have this class defined in my header:

class ConditionalLock
{
public:
    ConditionalLock(eastl::function<bool()> condition);
    ~ConditionalLock();

private:        
    static std::mutex s_mtx;
    static bool s_shouldLock;
    static bool s_lockInit;
};

.cpp looks like this:

ConditionalLock::ConditionalLock(std::function<bool()> condition)
{
    if (!s_lockInit)
    {
        if (condition())
            s_shouldLock = true;

        s_lockInit = true;
    }

    if (s_shouldLock)
        s_mtx.Lock();
}

ConditionalLock::~ConditionalLock()
{
    if (s_shouldLock)
        s_mtx.Unlock();
}

This conditional lock does the trick if I use it in only one place, concerning the fact that it contains three static members that track everything I need. However, I want to have a generic conditioned mutex that could be reused everywhere. What would be the right approach?

I thought about making a ConditionalMutexContext class that would be instantiated in the scope of the object where I want to use this mutex, and that config would contain these properties.

Something like this:

class ConditionalLockContext 
{
public:
    ConditionalLockContext(
        std::function<bool()> condition)
    : m_condition(condition)

private: 
    std::function<bool()> m_condition;
    bool m_shouldLock;
    bool m_lockInit;
}

And then pass the ConditionalLockContext instance to the conditional lock by reference.

Could you think of a better approach for this specific scenario?

You are confusing mutexes with locks. In C++, we implement RAII locking via (scoped) locks, mutexes do not have this behavior; look at std::mutex .

You want to implement a conditional scoped lock (derive from std::unique_lock , perhaps?). The state whether it locked something is separated from the state of the mutex.

In any case, I do not see a reason of having a shared state between all mutex instances, because that is exactly what static means... On the other hand, a mutex should be shared by lock instances, but not all of them. Thus, you want locks to refer to mutexes.

If you do not want to derive from std::unique_lock ( private -ly, of course), remove all static specifiers , and change the member mutex so that it is a reference that is provided during the construction of the lock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM