-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockQueue.cpp
More file actions
68 lines (59 loc) · 1.65 KB
/
Copy pathLockQueue.cpp
File metadata and controls
68 lines (59 loc) · 1.65 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
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <iostream>
#include <ostream>
#include <chrono>
#include <mutex>
#include <assert.h>
using namespace std;
class Queue {
typedef struct node_t {
int value;
struct node_t* next;
} note_t;
node_t *head;
node_t *tail;
pthread_mutex_t head_lock, tail_lock;
public :
Queue() {
node_t *tmp = (node_t *) malloc(sizeof(node_t));
tmp->next = NULL;
head = tail = tmp;
pthread_mutex_init(&head_lock, NULL);
pthread_mutex_init(&tail_lock, NULL);
}
void enqueue(int value) {
node_t *tmp = (node_t *) malloc(sizeof(node_t));
assert(tmp != NULL);
tmp->value = value;
tmp->next = NULL;
pthread_mutex_lock(&tail_lock);
tail->next = tmp;
tail = tmp;
pthread_mutex_unlock(&tail_lock);
}
int dequeue(int *value) {
pthread_mutex_lock(&head_lock);
node_t *tmp = head;
node_t *new_head = tmp->next;
if (new_head == NULL) {
pthread_mutex_unlock(&head_lock);
return -1; // queue was empty
}
*value = new_head->value;
head = new_head;
pthread_mutex_unlock(&head_lock);
free(tmp);
return 0;
}
int peek() {
int val = 0;
pthread_mutex_lock(&head_lock);
if (head != NULL )
val = head->value;
pthread_mutex_unlock(&head_lock);
return val;
}
};