-
Notifications
You must be signed in to change notification settings - Fork 216
/
queue_lock_mutex.c
71 lines (57 loc) · 1.32 KB
/
queue_lock_mutex.c
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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "queue.h"
#define QUEUE_POISON1 ((void*)0xCAFEBAB5)
struct queue_root {
struct queue_head *head;
pthread_mutex_t head_lock;
struct queue_head *tail;
pthread_mutex_t tail_lock;
struct queue_head divider;
};
struct queue_root *ALLOC_QUEUE_ROOT()
{
struct queue_root *root = \
malloc(sizeof(struct queue_root));
pthread_mutex_init(&root->head_lock, NULL);
pthread_mutex_init(&root->tail_lock, NULL);
root->divider.next = NULL;
root->head = &root->divider;
root->tail = &root->divider;
return root;
}
void INIT_QUEUE_HEAD(struct queue_head *head)
{
head->next = QUEUE_POISON1;
}
void queue_put(struct queue_head *new,
struct queue_root *root)
{
new->next = NULL;
pthread_mutex_lock(&root->tail_lock);
root->tail->next = new;
root->tail = new;
pthread_mutex_unlock(&root->tail_lock);
}
struct queue_head *queue_get(struct queue_root *root)
{
struct queue_head *head, *next;
while (1) {
pthread_mutex_lock(&root->head_lock);
head = root->head;
next = head->next;
if (next == NULL) {
pthread_mutex_unlock(&root->head_lock);
return NULL;
}
root->head = next;
pthread_mutex_unlock(&root->head_lock);
if (head == &root->divider) {
queue_put(head, root);
continue;
}
head->next = QUEUE_POISON1;
return head;
}
}