close

http://codereview.stackexchange.com/questions/28083/mutex-implementation

 

class Mutex
{
    private:
        volatile unsigned long long interlock;
    public:
        Mutex();
        ~Mutex();
    private:
        // These should be private to prevent locks being obtained
        // in a way that makes them exception unsafe.
        void lock();
        void unlock();

        // Need a friend that can lock and unlock the Mutex safely and correctly.
        friend class Locker;
};

class Locker
{
     Mutex&    m;
     public:
         Locker(Mutex& m): m(m) {m.lock();}
         ~Locker()              {m.unlock();}
};

// Usage
int main()
{
    Mutex    m;
    for(;;)
    {
        Locker lock(m);   // Locks the mutex (and gurantees it will be released)
                          // Even if there is an exception
    }
}

arrow
arrow
    全站熱搜

    hedgezzz 發表在 痞客邦 留言(0) 人氣()