Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <thread>
- #include <memory>
- using namespace std;
- class KeyValueStore {
- public:
- KeyValueStore() {
- // If there is no snapshotting:
- // write_ahead_log_helper_.locateToBeginning();
- // int key;
- // int value;
- // while (write_ahead_log_helper_.hasNext()) {
- // write_ahead_log_helper_.next(&key, &value);
- // map_[key] = value;
- // }
- // If there is snapshotting:
- // map_snapshotter_.recoverFromLatestSnapshot(&map_, ¤t_version_id_);
- // write_ahead_log_helper_.locateToVersion(current_version_id_);
- // int key;
- // int value;
- // while (write_ahead_log_helper_.hasNext()) {
- // write_ahead_log_helper_.next(&key, &value);
- // map_[key] = value;
- // ++current_version_id_;
- // ++num_writes_since_last_snapshot_;
- // }
- }
- bool put(int key, int value) {
- acquireWriteLock();
- // write_ahead_log_helper_.append(current_version_id_, "put," + key + "," + value);
- // ++current_version_id_;
- // ++num_writes_since_last_snapshot_;
- // Snapshot the map once every 1000 writes.
- // bool should_create_snapshot = false;
- // if (num_writes_since_last_snapshot_ >= 1000) {
- // should_create_snapshot = true;
- // }
- map_[key] = value;
- releaseWriteLock();
- // if (should_create_snapshot) {
- // acquireReadLock();
- // num_writes_since_last_snapshot_ = 0;
- // map_snapshotter_.createSnapshot(map_, current_version_id_);
- // releaseReadLock();
- // }
- return true;
- }
- bool get(int key, int* value) {
- bool is_successful = false;
- acquireReadLock();
- auto it = map_.find(key);
- if (it != map_.end()) {
- is_successful = true;
- *value = it->second;
- }
- releaseReadLock();
- return is_successful;
- }
- private:
- void acquireReadLock() {
- unique_lock<mutex> lock(mutex_);
- cv_.wait(lock, [this] {return !has_write_thread_;});
- num_read_threads_ += 1;
- }
- void releaseReadLock() {
- unique_lock<mutex> lock(mutex_);
- num_read_threads_ -= 1;
- if (num_read_threads_ == 0) {
- cv_.notify_all();
- }
- }
- void acquireWriteLock() {
- unique_lock<mutex> lock(mutex_);
- cv_.wait(lock, [this] {return !has_write_thread_ && num_read_threads_ == 0;});
- has_write_thread_ = true;
- }
- void releaseWriteLock() {
- unique_lock<mutex> lock(mutex_);
- has_write_thread_ = false;
- cv_.notify_all();
- }
- map<int, int> map_;
- // WriteAheadLogHelper write_ahead_log_helper_;
- // MapSnapshotter map_snapshotter_;
- // int current_version_id_ = 0;
- // int num_writes_since_last_snapshot_ = 0;
- bool has_write_thread_ = false;
- bool num_read_threads_ = 0;
- mutex mutex_;
- condition_variable cv_;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement