/************************************************************************
 * AUTHOR: NiuJiuRu
 * FILENAME: sw_rwlock.c
 * DESCRIPTION: 读写锁, 也称共享锁
 * NOTE: 主要用于多线程同步访问全局共享资源
 * HISTORY:
 * 1, [2014-01-24] created by NiuJiuRu
 ***********************************************************************/
#include "swapi.h"
#include "swmem.h"
#include "sw_rwlock.h"

/* 创建读写锁 */
void *sw_rwlock_create()
{
    pthread_rwlock_t *rwlock = NULL;
    pthread_rwlockattr_t attr;
    
    rwlock = (pthread_rwlock_t *)sw_heap_malloc(sizeof(pthread_rwlock_t));
    if(rwlock)
    {
        memset(rwlock, 0, sizeof(pthread_rwlock_t));
        pthread_rwlockattr_init(&attr);
        // note: "If the process-shared attribute is PTHREAD_PRO-CESS_PRIVATE, the read-write lock shall only be 
        // operated upon by threads created within the same process as the thread that initialized the read-write lock;
        // if threads of differing processes attempt to operate on such a read-write lock, the behavior is undefined."
        if(pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE) == 0) pthread_rwlock_init(rwlock, &attr);
        else{ sw_heap_free(rwlock); rwlock = NULL; }
        pthread_rwlockattr_destroy(&attr);
    }
    
    return rwlock;
}

/* 销毁读写锁 */
void sw_rwlock_destroy(void *hRWLock)
{
    pthread_rwlock_t *rwlock = (pthread_rwlock_t *)hRWLock;
    pthread_rwlock_destroy(rwlock);
    sw_heap_free(rwlock);
}

/* 读写锁上锁-读(超时设置的时间单位为: 毫秒, 并且当timeout = -1时表示无限等待) */
int sw_rwlock_rdlock(void *hRWLock, int timeout)
{
    pthread_rwlock_t *rwlock = (pthread_rwlock_t *)hRWLock;
    struct timespec ts = { 0 };
    
    if(timeout < 0)
    {
        return pthread_rwlock_rdlock(rwlock);
    }
    else
    {
        ts.tv_sec = time(NULL) + timeout/1000;
        ts.tv_nsec = (timeout%1000)*1000;
        if(pthread_rwlock_timedrdlock(rwlock, &ts) != 0) return -1;
    }
    
    return 0;
}

/* 读写锁上锁-写(超时设置的时间单位为: 毫秒, 并且当timeout = -1时表示无限等待) */
int sw_rwlock_wrlock(void *hRWLock, int timeout)
{
    pthread_rwlock_t *rwlock = (pthread_rwlock_t *)hRWLock;
    struct timespec ts = { 0 };
    
    if(timeout < 0)
    {
        return pthread_rwlock_wrlock(rwlock);
    }
    else
    {
        ts.tv_sec = time(NULL) + timeout/1000;
        ts.tv_nsec = (timeout%1000)*1000;
        if(pthread_rwlock_timedwrlock(rwlock, &ts) != 0) return -1;
    }
    
    return 0;
}

/* 读写锁解锁 */
void sw_rwlock_unlock(void *hRWLock)
{
    pthread_rwlock_t *rwlock = (pthread_rwlock_t *)hRWLock;
    pthread_rwlock_unlock(rwlock);
}
