Program Listing for File lock.h

Return to documentation for file (src/misc/pv/lock.h)

/* lock.h */
/*
 * Copyright information and license terms for this software can be
 * found in the file LICENSE that is included with the distribution
 */
#ifndef LOCK_H
#define LOCK_H

#include <stdexcept>

#include <epicsMutex.h>
#include <shareLib.h>

#include <pv/noDefaultMethods.h>


/* This is based on item 14 of
 * Effective C++, Third Edition, Scott Meyers
 */

// TODO reference counting lock to allow recursions

namespace epics { namespace pvData {

typedef epicsMutex Mutex;

class Lock {
    EPICS_NOT_COPYABLE(Lock)
public:
    explicit Lock(Mutex &m)
    : mutexPtr(m), locked(true)
    { mutexPtr.lock();}
    ~Lock(){unlock();}
    void lock()
    {
        if(!locked)
        {
            mutexPtr.lock();
            locked = true;
        }
    }
    void unlock()
    {
        if(locked)
        {
            mutexPtr.unlock();
            locked=false;
        }
    }
    bool tryLock()
    {
         if(locked) return true;
         if(mutexPtr.tryLock()) {
             locked = true;
             return true;
         }
         return false;
    }
    bool ownsLock() const{return locked;}
private:
    Mutex &mutexPtr;
    bool locked;
};


}}
#endif  /* LOCK_H */