Locker.cpp 1.42 KB
Newer Older
oscar's avatar
oscar committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#include "Locker.h"

#include <pthread.h>


namespace jf {

Locker::Locker() {
    pthread_mutexattr_t mutex_attr;
    int nRet = pthread_mutexattr_init(&mutex_attr);
    if (nRet) {
        throw "init mutex attr error";
    }
    nRet = pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE);
    if (nRet) {
        throw "pthread_mutexattr_settype error";
    }
    nRet = pthread_mutex_init(&m_mutex, &mutex_attr);
    if (nRet) {
        throw "pthread_mutex_init error";
    }
    pthread_mutexattr_destroy(&mutex_attr);
}

Locker::~Locker() { pthread_mutex_destroy(&m_mutex); }

void Locker::lock(int type) { pthread_mutex_lock(&m_mutex); }

void Locker::unlock() { pthread_mutex_unlock(&m_mutex); }

RWLocker::RWLocker() {
    int nRet = 0;
    // 	pthread_rwlockattr_t mutex_attr;
    // 	nRet = pthread_rwlockattr_init(&mutex_attr);
    // 	if(nRet){
    // 		throw "init mutex attr error";
    // 	}
    // 	//д
    // 	pthread_rwlockattr_setkind_np (&mutex_attr,PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
    nRet = pthread_rwlock_init(&m_mutex, NULL);
    if (nRet) {
        throw "pthread_mutex_init error";
    }
}

RWLocker::~RWLocker() { pthread_rwlock_destroy(&m_mutex); }

void RWLocker::lock(int type) {
    if (0 == type) {
        pthread_rwlock_rdlock(&m_mutex);
    } else {
        pthread_rwlock_wrlock(&m_mutex);
    }
}

void RWLocker::unlock() { pthread_rwlock_unlock(&m_mutex); }

}  // namespace jf