Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1075213
  • 博文数量: 77
  • 博客积分: 11498
  • 博客等级: 上将
  • 技术积分: 1840
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-04 11:10
文章分类

全部博文(77)

文章存档

2011年(1)

2010年(16)

2009年(5)

2008年(55)

分类: C/C++

2008-11-18 20:43:16


    实现一个Windows下的共享锁(读写锁)(二)
    作者:tyc611.cublog.cn,2008-11-18
接上篇《实现一个Windows下的共享锁(读写锁)(一)》

在上篇中,我们已经实现了一个基本的共享锁SharedMutex,提供了共享访问和独占访问的功能。本篇在SharedMutex的基础上,包装出一个更加方便的共享锁SharedLock,并利用类型别名来提供读锁和写锁。

源代码如下(完整代码打包下载见文章底部)

/**
* SharedLock.h
* @Author Tu Yongce
* @Created 2008-11-17
* @Modified 2008-11-17
* @Version 0.1
*/


#ifndef SHARED_LOCK_H_INCLUDED
#define SHARED_LOCK_H_INCLUDED

#include <stdexcept>
#include <string>
#include "SharedMutex.h"
#include "Noncopyable.h"

// lock exception class
class LockError: public std::logic_error
{
public:
    explicit LockError(const std::string &msg): std::logic_error(msg) {}
};

// shared policy
class SharedPolicy
{
private:
    SharedMutex &m_mutex;
    bool m_locked;

protected:
    // disallow instantiation
    SharedPolicy(SharedMutex &mutex): m_mutex(mutex), m_locked(false)
    {
    }

    void LockWithNoChecking()
    {
        m_mutex.AcquireShared();
        m_locked = true;
    }

    void UnlockWithNoChecking()
    {
        m_mutex.ReleaseShared();
        m_locked = false;
    }

    bool OwnLock() const
    {
        return m_locked;
    }
};

// exclusive policy
class ExclusivePolicy
{
private:
    SharedMutex &m_mutex;
    bool m_locked;

protected:
    // disallow instantiation
    ExclusivePolicy(SharedMutex &mutex): m_mutex(mutex), m_locked(false)
    {
    }

    void LockWithNoChecking()
    {
        m_mutex.AcquireExclusive();
        m_locked = true;
    }

    void UnlockWithNoChecking()
    {
        m_mutex.ReleaseExclusive();
        m_locked = false;
    }

    bool OwnLock() const
    {
        return m_locked;
    }
};

// shared lock
template <class LockPolicy>
class SharedLock
    : private LockPolicy, private Noncopyable
{
public:
    explicit SharedLock(SharedMutex &mutex, bool lock = true): LockPolicy(mutex)
    {
        if (lock) {
            LockWithNoChecking();
        }
    }

    ~SharedLock()
    {
        if (OwnLock()) {
            UnlockWithNoChecking();
        }
    }

    void Lock()
    {
        if (OwnLock()) {
            throw LockError("already owned the lock when called Lock()");
        }

        LockWithNoChecking();
    }

    void Unlock()
    {
        if (!OwnLock()) {
            throw LockError("did NOT own the lock when called Unlock()");
        }

        UnlockWithNoChecking();
    }
};

// read lock
typedef SharedLock<SharedPolicy> ReadLock;

// write lock
typedef SharedLock<ExclusivePolicy> WriteLock;

#endif // SHARED_LOCK_H_INCLUDED


源代码打包下载:

文件:SharedLock.zip
大小:3KB
下载:下载


阅读(1978) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~