Commit 4fbaf0a8 authored by Shivaji's avatar Shivaji

Merge branch 'lru-sample' into 'master'

Lru sample

See merge request !1
parents 6dec1e51 996cb357
......@@ -6,6 +6,7 @@
#include <unistd.h>
#include <string.h>
#include <stdatomic.h>
#include <assert.h>
#include "LRU.h"
#define ATOMIC_TEST_AND_SET __atomic_test_and_set
#define CLEAR __atomic_clear
......@@ -13,7 +14,7 @@
struct KV *array[MAX_SIZE];
struct queue *qu;
struct queue *qu=NULL;
struct queue *last;
......@@ -22,15 +23,24 @@ struct queue *last;
void remove_element_from_deque(char *key)
{
queue *present = qu , *previous=NULL;
if(present == NULL)
return;
if(strcmp(present->key, key) == 0)
{
qu = qu->next;
if(last == present)
last = last->next;
free(present);
return;
}
while(present->next != NULL)
{
if(present->key == key)
if(strcmp(present->key, key) == 0)
{
if(previous == NULL)
qu = qu->next;
if(last == present)
last = previous;
if(previous)
previous->next = present->next;
free(present);
return;
......@@ -43,7 +53,7 @@ void remove_element_from_deque(char *key)
void insert_into_queue(char *key)
{
queue *temp = (queue *)malloc(sizeof(queue));
temp->key = key;
memcpy(temp->key, key, KEY_SIZE);
temp->next = NULL;
if(qu == NULL)
{
......@@ -57,6 +67,23 @@ void insert_into_queue(char *key)
}
}
int remove_front_element()
{
queue *temp = qu;
qu = qu->next;
assert(temp != NULL);
assert(qu != NULL);
for(int i=0;i<MAX_SIZE;i++)
{
if(strcmp(array[i]->key , temp->key) == 0)
{
// check if it is modified to write to file
array[i]->valid = FALSE;
return i;
}
}
}
int find_empty_location()
{
for(int i=0;i<MAX_SIZE;i++)
......@@ -64,6 +91,7 @@ int find_empty_location()
if(array[i]->valid == FALSE)
return i;
}
return remove_front_element();
}
int cache_del(char *key)
......@@ -93,6 +121,7 @@ void cache_put(char *key, char *value)
if(array[i]->key!=NULL) {
if(strcmp(array[i]->key , key) == 0)
{
printf("ENTERING INTO QUEUE\n");
indx = i;
remove_element_from_deque(key);
break;
......@@ -104,6 +133,7 @@ void cache_put(char *key, char *value)
if(indx == -1)
{
indx = find_empty_location();
assert(indx>=0);
// TODO should write to file if modified is true
// replacment from cache
}
......@@ -115,7 +145,6 @@ void cache_put(char *key, char *value)
array[indx]->modified = TRUE;
insert_into_queue(key);
CLEAR(&(array[indx]->lock),0);
printf("Cache after PUT: \n");
print_cache();
}
......
......@@ -22,7 +22,7 @@ typedef struct KV KV;
typedef struct queue queue;
struct queue{
char *key;
char key[KEY_SIZE];
struct queue *next;
};
......@@ -45,3 +45,5 @@ int cache_get(char *key, char *value);
void init_cache();
void print_cache();
int remove_front_element();
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment