c++counting semaphore 处理读写问题
时间: 2023-08-07 20:07:46 浏览: 134
C++ 读写者问题
在 C++ 中处理读写问题可以使用计数信号量(counting semaphore)。计数信号量是一种允许多个线程同时访问共享资源的同步机制,它允许一定数量的线程同时进入关键区域,当达到最大并发数时,后续线程需要等待其他线程退出关键区域后才能进入。
对于读写问题,可以使用两个计数信号量,一个用于控制读的并发数,一个用于控制写的并发数。具体实现可以参考以下示例代码:
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
using namespace std;
class CountingSemaphore {
public:
CountingSemaphore(int count) : count_(count) {}
void acquire() {
unique_lock<mutex> lock(mutex_);
while (count_ == 0) {
cv_.wait(lock);
}
count_--;
}
void release() {
unique_lock<mutex> lock(mutex_);
count_++;
cv_.notify_one();
}
private:
int count_;
mutex mutex_;
condition_variable cv_;
};
class ReaderWriterLock {
public:
ReaderWriterLock() : read_count_(0), write_count_(0), read_sem_(1), write_sem_(1) {}
void read_lock() {
read_sem_.acquire();
unique_lock<mutex> lock(mutex_);
read_count_++;
if (read_count_ == 1) {
write_sem_.acquire();
}
read_sem_.release();
}
void read_unlock() {
unique_lock<mutex> lock(mutex_);
read_count_--;
if (read_count_ == 0) {
write_sem_.release();
}
}
void write_lock() {
write_sem_.acquire();
}
void write_unlock() {
write_sem_.release();
}
private:
int read_count_;
int write_count_;
CountingSemaphore read_sem_;
CountingSemaphore write_sem_;
mutex mutex_;
};
ReaderWriterLock rw_lock;
void read_func(int id) {
while (true) {
rw_lock.read_lock();
cout << "Reader " << id << " is reading" << endl;
this_thread::sleep_for(chrono::milliseconds(1000));
rw_lock.read_unlock();
}
}
void write_func(int id) {
while (true) {
rw_lock.write_lock();
cout << "Writer " << id << " is writing" << endl;
this_thread::sleep_for(chrono::milliseconds(2000));
rw_lock.write_unlock();
}
}
int main() {
thread readers[5], writers[2];
for (int i = 0; i < 5; i++) {
readers[i] = thread(read_func, i);
}
for (int i = 0; i < 2; i++) {
writers[i] = thread(write_func, i);
}
for (int i = 0; i < 5; i++) {
readers[i].join();
}
for (int i = 0; i < 2; i++) {
writers[i].join();
}
return 0;
}
```
在上述代码中,`CountingSemaphore` 类是一个计数信号量,通过 `acquire()` 和 `release()` 方法实现信号量的加锁和解锁操作。`ReaderWriterLock` 类是一个读写锁,通过 `read_lock()`、`read_unlock()`、`write_lock()` 和 `write_unlock()` 方法实现读写锁的加锁和解锁操作。在 `read_lock()` 和 `read_unlock()` 方法中,先使用 `read_sem_` 控制读的并发数,再使用 `mutex_` 控制共享变量的访问。在 `write_lock()` 和 `write_unlock()` 方法中,直接使用 `write_sem_` 控制写的并发数。在 `main()` 函数中,创建了 5 个读线程和 2 个写线程,并启动它们。运行程序后,可以看到读线程和写线程交替执行,且同一时刻只有一个写线程或多个读线程在执行。
阅读全文