14

问答题 14 /50

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

参考答案

下面是可参考的伪代码:
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);
}

牛客网,程序员必备求职神器
QQ群:169195721
微 信:www_nowcoder_com 关注
微 博:牛客网 关注

扫一扫,把题目装进口袋