如何在FreeBSD中创建进程间rwlock?

时间:2012-03-12 16:19:35

标签: locking ipc freebsd rwlock

在FreeBSD中进行进程间读写锁的方法是什么?我正在寻找类似pthread的rwlock的东西,可以通过“pthread_rwlockattr_setpshared”和在Linux中成功运行的PTHREAD_PROCESS_SHARED标志在进程之间共享。但是FreeBSD不支持这个标志。提前谢谢。

1 个答案:

答案 0 :(得分:0)

在这里找到了一个基于posix信号量的简单易用的解决方案: http://stupefydeveloper.blogspot.com/2009/03/nix-rw-lock-with-semaphores.html

#include <semaphore.h>
#include <errno.h>

struct rwlock {
    sem_t rlock;
    sem_t wlock;
};

void init_rwlock(struct rwlock *rw) {
    sem_init(&rw->rlock, 1, 0);
    sem_init(&rw->wlock, 1, 1);
}

void destroy_rwlock(struct rwlock *rw) {
    wlock(rw);
    sem_destroy(&rw->rlock);
    sem_destroy(&rw->wlock);
}

void rlock(struct rwlock *rw){
    sem_wait(&rw->wlock);
    sem_post(&rw->rlock);
    sem_post(&rw->wlock);
}

void wlock(struct rwlock *rw) {
    int readers = 0;
    sem_wait(&rw->wlock);

    do {
        if (sem_getvalue(&rw->rlock, &readers) != -1) {
            if (readers == 0)
                break;
        }
        usleep(1);
    } while (1);
}

void runlock(struct rwlock *rw) {
    do {
        if (sem_trywait(&rw->rlock) == -1) {
            if (errno != EAGAIN)
                continue;
        }
        break;
    } while (1);
}

void wunlock(struct rwlock *rw) {
    sem_post(&rw->wlock);
}