Windows 平台之读写锁

来源:互联网 发布:ansys软件安装 编辑:程序博客网 时间:2024/05/16 19:37
//windows平台下使用临界段实现的读写锁功能,代码短小简洁。导出函数名使用POSIX函数名

///By Fanxiushu 2012

#pragma once

#ifdef WIN32

#include <stdio.h>
#include <assert.h>
#include <windows.h>
/////读写锁
struct rwlock
{
private:
    CRITICAL_SECTION write_lock;
    CRITICAL_SECTION read_lock;
    volatile LONG     reader_count;
    volatile bool        is_enter_writer;
public:
    rwlock(){
        reader_count = 0;
        is_enter_writer = false;
        ::InitializeCriticalSection( &write_lock);
        ::InitializeCriticalSection(&read_lock);
    }
    ~rwlock(){
        ::DeleteCriticalSection(&write_lock);
        ::DeleteCriticalSection(&read_lock);
    }

public:
    int rdlock(){
        EnterCriticalSection( &write_lock );
        if( ::InterlockedIncrement( &reader_count ) == 1 ){
            EnterCriticalSection( &read_lock );
        }
        LeaveCriticalSection( &write_lock );

        return 0;
    }
    int wrlock(){
        EnterCriticalSection( &write_lock );
        EnterCriticalSection( &read_lock);
        is_enter_writer = true;
        return 0;
    }
    void _unlock() {
        if( is_enter_writer ){
            is_enter_writer = false;
            LeaveCriticalSection( &read_lock );
            LeaveCriticalSection( &write_lock );
        }
        else{
            if( ::InterlockedDecrement( &reader_count) == 0 ){
                LeaveCriticalSection( &read_lock );
            }
        }
    }
   ///////////
};

typedef rwlock  pthread_rwlock_t;

#define  pthread_rwlock_init( l )
#define  pthread_rwlock_destroy(l)
#define  pthread_rwlock_rdlock( l )            ((rwlock*)(l))->rdlock()
#define  pthread_rwlock_wrlock( l )           ((rwlock*)(l))->wrlock()
#define  pthread_rwlock_unlock( l )           ((rwlock*)(l))->_unlock()

#else
#include <unistd.h>
#include <pthread.h>
#endif
原创粉丝点击