首页 > 试题广场 >

请用普通的互斥锁编程实现一个读写锁

[问答题]
请用普通的互斥锁编程实现一个读写锁
下面是可参考的伪代码:
count_mutex = mutex_init();
write_mutex = mutex_init();
read_count = 0;

void read_lock {
 lock(count_mutex);
 read_count++;
 if (read_count == 1) {
  lock(write_mutex);
 }
 unlock(count_mutex);
}

void read_unlock {
 lock(count_mutex);
 read_count--;
 if (read_count == 0) {
  unlock(write_mutex);
 }
 unlock(count_mutex);
}

void write_lock {
 lock(write_mutex);
}

void write_unlock {
 unlock(write_mutex);
}

发表于 2015-05-05 14:44:40 回复(1)
pcd头像 pcd
以下为实现与演示
#include <stdio.h>
#include <pthread.h>
#include <time.h>

pthread_mutex_t read_mutex;
pthread_mutex_t write_mutex;
int read_count = 0;

void read_lock(){
    pthread_mutex_lock(&read_mutex);
    read_count++;
    if(read_count==1){
        pthread_mutex_lock(&write_mutex);
    }
    pthread_mutex_unlock(&read_mutex);
}

void read_unlock(){
    read_count--;
    if(read_count==0){
        pthread_mutex_unlock(&write_mutex);
    }
}

void write_lock(){
    pthread_mutex_lock(&write_mutex);
}

void write_unlock(){
    pthread_mutex_unlock(&write_mutex);
}

void* fun1(void* v){
    read_lock();
    int i;
    for(i=0; i<10 ;i++)
    {
        printf("reading A\n");
        sleep(1);
    
    }
    read_unlock();

    return NULL;
}

void* fun2(void* v){
    read_lock();
    int i;
    for(i=0; i<10 ;i++)
    {
        printf("reading B\n");
        sleep(1);
    }
    read_unlock();
    return NULL;
}

void* fun3(void* v){
    sleep(1);
    write_lock();
    printf("writing C\n");
    write_unlock();

    return NULL;
}

int main(int argc, char* argv[]){
    
    pthread_mutex_init(&read_mutex, NULL);
    pthread_mutex_init(&write_mutex, NULL);
    
    pthread_t p1,p2,p3;

    pthread_create(&p1, NULL, fun1, NULL);
    pthread_create(&p2, NULL, fun2, NULL);
    pthread_create(&p3, NULL, fun3, NULL);

    pthread_join(p1, NULL);
    pthread_join(p2, NULL);
    pthread_join(p3, NULL);

    pthread_mutex_destroy(&read_mutex);
    pthread_mutex_destroy(&write_mutex);

    return 0;
}

发表于 2018-05-07 11:06:25 回复(0)