-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash_table.cc
More file actions
53 lines (47 loc) · 981 Bytes
/
Copy pathhash_table.cc
File metadata and controls
53 lines (47 loc) · 981 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
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <algorithm>
#include <pthread.h>
#define MAX_SIZE 100
template<typename T>
class hash_table {
private:
std::vector<T> li[MAX_SIZE];
pthread_mutex_t lock;
public:
hash_table() {
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
}
void insert(T t) {
pthread_mutex_lock(&lock);
if (query(t) == 1) {
pthread_mutex_unlock(&lock);
return;
}
int idx = t % MAX_SIZE;
li[idx].push_back(t);
pthread_mutex_unlock(&lock);
}
int query(T t) {
pthread_mutex_lock(&lock);
int idx = t % MAX_SIZE;
if (std::find(li[idx].begin(), li[idx].end(), t) == li[idx].end()) {
pthread_mutex_unlock(&lock);
return 0;
}
pthread_mutex_unlock(&lock);
return 1;
}
};
int main(int argc, char *argv[]) {
hash_table<int> ht;
ht.insert(1);
ht.insert(2);
ht.insert(3);
ht.insert(4);
printf("%d\n", ht.query(5));
printf("%d\n", ht.query(4));
printf("%d\n", ht.query(1));
}