BS_Praktikum4/analysis_model.h

44 lines
939 B
C
Raw Normal View History

2025-06-03 00:50:08 +02:00
#pragma once
#include <mutex>
#include <condition_variable>
class AnalysisModel {
2025-06-03 01:49:23 +02:00
int value = 0;
int reader_count = 0;
2025-06-03 00:50:08 +02:00
2025-06-03 01:49:23 +02:00
std::mutex model_mutex;
std::mutex count_mutex;
std::condition_variable no_writer;
2025-06-03 00:50:08 +02:00
public:
int read() {
std::unique_lock<std::mutex> count_lock(count_mutex);
reader_count++;
if(reader_count == 1) {
model_mutex.lock();
}
count_lock.unlock();
int result = value;
count_lock.lock();
reader_count--;
if(reader_count == 0) {
model_mutex.unlock();
no_writer.notify_one();
}
return result;
}
void write(int new_value) {
std::unique_lock<std::mutex> lock(model_mutex);
value = new_value;
no_writer.wait(lock, [this]() {
return reader_count == 0;
});
}
2025-06-03 01:49:23 +02:00
};