使用信号量实现读写锁

使用信号量实现读写锁,第1张

struct rwlock

{

    sem_t read

    sem_t write

    int reads

}

void RWLock_Init(rwlock &lock)

{

    sem_init(lock.read, 0, 1)

    sem_init(lock.write, 0, 1)

    lock.reads = 0

}

void Acquir_read_lock(rwlock &lock)

{

    sem_wait(&lock.read)

    ++lock.reads

    if(lock.reads == 1)

    {

        sem_wait(&lock.write)

    }

    sem_post(&lock.write)

}

void acquir_read_unlock(rwlock &lock)

{

    sem_wait(&lock.read)

    --lock.reads

    if(lock.reads == 0)

    {

        sem_post(&lock.write)

    }

    sem_post(&lcok.read)

}

void acquir_write_lock(rwlock &lock)

{

    sem_wait(&lock.write)

}

void acquir_write_unlock(rwlock * lock)

{

    sem_post(&lock.write)

}

#include <semaphore.h>

int sem_wait(sem_t *sem)

int sem_trywait(sem_t *sem)

int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout)

Link with -lrt or -pthread.

自己看最后一句....手册里面写着呢....link with -lrt or -pthread


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/185810.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-03-29
下一篇2023-03-29

发表评论

登录后才能评论

评论列表(0条)

    保存