异步互斥锁

什么情况下需要用到锁呢,就是多线程在使用同一个资源(变量),比如,在类A中有一个变量int i,A创建了3个线程,i作为变量传递给了这3个线程,每个线程都需要对这i进行修改,那么在使用 i 的时候,这3个线程都需要进行锁操作。

第一步 声明纯虚类:

class Lock {
public:
    /**
     * 析构函数
     */
    virtual ~Lock() {}
   
    /**
     * 加锁
     */
    virtual void acquire() = 0;
   
    /**
     * 尝试加锁
     * @return 加锁成功则返回true, 否则返回false
     */
    virtual bool tryAcquire() = 0;
   
    /**
     * 解锁
     */
    virtual void release() = 0;
};

第二步 声明 锁类,继承纯虚类

class Mutex : public Lock{
public:
    /**
     * 构造函数
     */
    Mutex();
   
    /**
     * 析构函数
     */
    virtual ~Mutex();
   
    /**
     * 加锁
     */
    virtual void acquire();
   
    /**
     * 尝试加锁
     * @return 加锁成功则返回true, 否则返回false
     */
    virtual bool tryAcquire();
   
    /**
     * 解锁
     */
    virtual void release();
   
private:
    /**
     * 声明友元
     */
    friend class Condition;
   
protected:

    pthread_mutex_t     _mutex;
};

实现:

Mutex::Mutex() {
    pthread_mutexattr_t attr;
    int rc = pthread_mutexattr_init(&attr);
    if (rc) {
        throw SynchException(rc);
    }

    rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
    if (rc) {
        throw SynchException(rc);
    }

    rc = pthread_mutex_init(&_mutex, &attr);
    if (rc) {
        throw SynchException(rc);
    }

    rc = pthread_mutexattr_destroy(&attr);
    if(rc != 0) {
        throw SynchException(rc);
    }
}

Mutex::~Mutex() {

    int rc = pthread_mutex_destroy(&_mutex);
    if (rc) {
        cerr << "Failed to destroy mutex: " << SynchException::toString(rc) << endl;
    }
}

void Mutex::acquire() {

    int rc = pthread_mutex_lock(&_mutex);
    if (rc) {
        throw SynchException(rc);
    }
}

bool Mutex::tryAcquire() {

    int rc = pthread_mutex_trylock(&_mutex);
    if (rc != 0 && rc != EBUSY) {
        throw SynchException(rc);
    }
    return rc == 0;
}

void Mutex::release() {
    int rc = pthread_mutex_unlock(&_mutex);
    if (rc) {
        throw SynchException(rc);
    }
}

猜你喜欢

转载自konin.iteye.com/blog/2333350