I want to implement a multithreading LRU cache in C++. And here is the code. Can you tell me what should I do to make it more multithreading?
#include <iostream>
#include <unordered_map>
#include <thread>
#include <chrono>
#include <mutex>
using namespace std;
class LRUCache {
public:
class Node {
public:
int key,val;
Node* left,*right;
Node(int _key,int _val):key(_key),val(_val),left(NULL),right(NULL) {}
}*L,*R;
unordered_map<int,Node*> m;
int n;
mutex mtx;
condition_variable cv;
void insert(Node* node)
{
Node* next=L->right;
L->right=node;
node->right=next;
node->left=L;
next->left=node;
}
void erase(Node* node) {
node->left->right=node->right;
node->right->left=node->left;
}
LRUCache(int capacity) {
n=capacity;
L=new Node(-1,-1),R=new Node(-1,-1);
L->right=R;
R->left=L;
}
int get(int key) {
mtx.lock();
if(m.count(key)==0) {mtx.unlock();return -1;}
Node* node=m[key];
erase(node);
insert(node);
cout<<"get:"<<node->val<<endl;
mtx.unlock();
return node->val;
}
void put(int key, int value) {
mtx.lock();
if(m.count(key)) {
m[key]->val=value;
erase(m[key]);
insert(m[key]);
} else {
Node* node=new Node(key,value);
if(m.size()==n) {
Node* tmp=R->left;
erase(tmp);
m.erase(tmp->key);
}
insert(node);
m[key]=node;
}
cout<<"put:"<<value<<endl;
mtx.unlock();
}
void putcache() {
for(int i=1;i<=10;i++) {
put(i,i+10);
this_thread::sleep_for(std::chrono::seconds(1));
}
}
void getcache() {
for(int i=1;i<=10;i++) {
get(i);
this_thread::sleep_for(std::chrono::seconds(1));
}
}
};
int main() {
LRUCache c1(100);
std::thread t1(&LRUCache::putcache,&c1);
std::thread t2(&LRUCache::getcache,&c1);
t1.join();
t2.join();
}