#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