-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.cpp
More file actions
45 lines (37 loc) · 971 Bytes
/
cache.cpp
File metadata and controls
45 lines (37 loc) · 971 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// cache.cpp
#include "cache.h"
#include <iostream>
using namespace std;
Cache::Cache(int shard_count, int shard_size){
// initialize shards
buckets.reserve(shard_count);
for(int i = 0; i < shard_count; i++){
buckets.emplace_back(shard_size);
}
this->shard_count = shard_count;
}
uint32_t hash_int(uint32_t x) {
x = ((x >> 16) ^ x) * 0x45d9f3b;
x = ((x >> 16) ^ x) * 0x45d9f3b;
x = (x >> 16) ^ x;
return x;
}
int Cache::get_idx(int key){
return (unsigned int)key % this->shard_count;
}
int Cache::get(int key){
int idx = get_idx(key);
lock_guard<mutex> lock(*(buckets[idx].lock));
int res = buckets[idx].shard.get(key);
return res;
}
void Cache::set(int key, int value){
int idx = get_idx(key);
lock_guard<mutex> lock(*(buckets[idx].lock));
buckets[idx].shard.set(key, value);
}
void Cache::remove(int key){
int idx = get_idx(key);
lock_guard<mutex> lock(*(buckets[idx].lock));
buckets[idx].shard.remove(key);
}