-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
67 lines (61 loc) · 1.57 KB
/
queue.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
//
// Created by lklake on 2019/7/5.
//
#include <malloc.h>
#include "queue.h"
void queue_init(queue* this){
this->destroy=&queue_destroy;
this->enqueue=&queue_enqueue;
this->isempty=&queue_isempty;
this->top=&queue_top;
this->dequeue=&queue_dequeue;
this->head=(queue_node*)malloc(sizeof(queue_node));
this->tail=(queue_node*)malloc(sizeof(queue_node));
this->head->next=this->tail;
this->tail->next=NULL;
this->size=0;
pthread_mutex_init(&this->mutex,NULL);
}
void queue_enqueue(queue* this,void* data){
pthread_mutex_lock(&this->mutex);
this->tail->data=data;
this->tail->next=(queue_node*)malloc(sizeof(queue_node));
this->tail=this->tail->next;
this->tail->next=NULL;
this->size++;
pthread_mutex_unlock(&this->mutex);
}
void queue_dequeue(queue* this){
if(this->size>0){
pthread_mutex_lock(&this->mutex);
queue_node* tmp=this->head;
this->head=this->head->next;
free(tmp);
tmp=NULL;
this->size--;
pthread_mutex_unlock(&this->mutex);
}
}
void* queue_top(queue* this){
if(this->size>0)
return this->head->next->data;
else{
printf("empty queue\n");
}
}
void queue_destroy(queue* this){
pthread_mutex_lock(&this->mutex);
queue_node* tmp=this->head;
while(tmp->next){
this->head=this->head->next;
free(tmp);
tmp=this->head;
}
pthread_mutex_unlock(&this->mutex);
pthread_mutex_destroy(&this->mutex);
}
int queue_isempty(queue* this){
if(this->size==0)
return 1;
return 0;
}