c++实现读者写作(读者优先)代码
时间: 2023-08-06 20:15:41 浏览: 141
读者写者问题c++实现
5星 · 资源好评率100%
好的,下面是读者写者(读者优先)算法的C++实现代码:
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <chrono>
using namespace std;
mutex mtx;
condition_variable cv_reader, cv_writer;
int reader_count = 0;
bool writing = false;
void reader(int id) {
unique_lock<mutex> lock(mtx);
while (writing) {
cv_reader.wait(lock);
}
reader_count++;
cout << "读者" << id << "开始读取,当前读者数:" << reader_count << endl;
lock.unlock();
this_thread::sleep_for(chrono::seconds(1));
lock.lock();
reader_count--;
cout << "读者" << id << "读取完毕,当前读者数:" << reader_count << endl;
if (reader_count == 0) {
cv_writer.notify_one();
}
lock.unlock();
}
void writer(int id) {
unique_lock<mutex> lock(mtx);
while (writing || reader_count > 0) {
cv_writer.wait(lock);
}
writing = true;
cout << "写者" << id << "开始写入" << endl;
lock.unlock();
this_thread::sleep_for(chrono::seconds(1));
lock.lock();
writing = false;
cout << "写者" << id << "写入完毕" << endl;
cv_reader.notify_all();
cv_writer.notify_one();
lock.unlock();
}
int main() {
int n_reader, n_writer;
cout << "请输入读者和写者的数量:" << endl;
cin >> n_reader >> n_writer;
vector<thread> threads;
for (int i = 0; i < n_reader; i++) {
threads.push_back(thread(reader, i));
}
for (int i = 0; i < n_writer; i++) {
threads.push_back(thread(writer, i));
}
for (auto& t : threads) {
t.join();
}
return 0;
}
```
这段代码实现了读者写者(读者优先)算法,其中使用了互斥锁和条件变量来实现读者和写者的同步。读者和写者都使用了一个互斥锁,读者使用了一个条件变量来实现读者优先,即读者在读取时不会被写者打断,而写者必须等待所有读者完成读取后才能写入。在实现过程中,我们使用了C++11提供的线程库,创建了多个读者和写者的线程,并使用join()函数等待所有线程执行完毕。
阅读全文