-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.c
More file actions
101 lines (86 loc) · 2.08 KB
/
Copy pathcache.c
File metadata and controls
101 lines (86 loc) · 2.08 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<stdio.h>
#include<stdlib.h>
#include <semaphore.h>
#include<string.h>
#include"structs.h"
extern sem_t LRU_lock;
struct LRUcache *initLRUcache(int capacity)
{
struct LRUcache *queue = (struct LRUcache *)malloc(sizeof(struct LRUcache));
queue->front = queue->rear = NULL;
queue->size = 0;
queue->capacity = capacity;
sem_init(&LRU_lock, 0, 1);
return queue;
}
void enqueue(struct LRUcache *queue, char *key, ss_info *value)
{
sem_wait(&LRU_lock);
if (queue->size == queue->capacity)
{
struct LRUNode *temp = queue->front;
queue->front = temp->next;
free(temp);
queue->size--;
}
struct LRUNode *newNode = (struct LRUNode *)malloc(sizeof(struct LRUNode));
strcpy(newNode->key, key);
newNode->value = value;
newNode->next = NULL;
if (queue->rear == NULL)
{
queue->front = queue->rear = newNode;
}
else
{
queue->rear->next = newNode;
queue->rear = newNode;
}
queue->size++;
sem_post(&LRU_lock);
}
void dequeue(struct LRUcache *queue, char *key)
{
sem_wait(&LRU_lock);
if (queue->front == NULL){
sem_post(&LRU_lock);
return;
}
struct LRUNode *temp = queue->front, *prev = NULL;
while (temp != NULL && strcmp(temp->key, key) != 0)
{
prev = temp;
temp = temp->next;
}
if (temp == NULL){
sem_post(&LRU_lock);
return;
}
if (prev == NULL)
queue->front = temp->next;
else
prev->next = temp->next;
if (temp == queue->rear)
queue->rear = prev;
free(temp);
queue->size--;
sem_post(&LRU_lock);
}
ss_info *getFromLRUcache(struct LRUcache *queue, char *key)
{
sem_wait(&LRU_lock);
struct LRUNode *temp = queue->front;
while (temp != NULL)
{
if (strcmp(temp->key, key) == 0)
{
sem_post(&LRU_lock);
dequeue(queue, key);
enqueue(queue, key, temp->value);
return temp->value;
}
temp = temp->next;
}
sem_post(&LRU_lock);
return NULL;
}