-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGQueue.go
More file actions
115 lines (102 loc) · 2.11 KB
/
Copy pathGQueue.go
File metadata and controls
115 lines (102 loc) · 2.11 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package ghostlib
/*****************************************
* FileName : GQueue.go
* Author : ghostwwl
* Note : 线程/Goroutine 安全的队列呢
*****************************************/
import (
"container/list"
"sync"
)
type Queue struct {
MaxSize uint32
UnfinishedTasks uint32
Mutex *sync.Mutex
NotEmpty *sync.Cond
NotFull *sync.Cond
AllTasksDone *sync.Cond
List *list.List
}
func NewQueue() *Queue {
obj := new(Queue)
obj.MaxSize = 0
obj.UnfinishedTasks = 0
obj.Mutex = new(sync.Mutex)
obj.NotEmpty = sync.NewCond(obj.Mutex)
obj.NotFull = sync.NewCond(obj.Mutex)
obj.AllTasksDone = sync.NewCond(obj.Mutex)
obj.List = list.New()
return obj
}
func (this *Queue) TaskDone() {
this.AllTasksDone.L.Lock()
defer func() {
err := recover()
if err != nil {
this.AllTasksDone.L.Unlock()
panic(err)
}
}()
unfinished := this.UnfinishedTasks - 1
if unfinished <= 0 {
if unfinished < 0 {
panic("called too many times")
}
this.AllTasksDone.Broadcast()
this.UnfinishedTasks = unfinished
}
this.AllTasksDone.L.Unlock()
}
func (this *Queue) Join() {
this.AllTasksDone.L.Lock()
for {
if this.UnfinishedTasks > 0 {
this.AllTasksDone.Wait()
} else {
break
}
}
this.AllTasksDone.L.Unlock()
}
func (this *Queue) Qsize() int {
this.Mutex.Lock()
n := this.List.Len()
this.Mutex.Unlock()
return n
}
func (this *Queue) IsEmpty() bool {
if this.Qsize() > 0{
return false
}
return true
}
func (this *Queue) IsFull() bool {
this.Mutex.Lock()
n := this.List.Len()
r := n > 0 && uint32(n) == this.MaxSize
this.Mutex.Unlock()
return r
}
func (this *Queue) Put(item interface{}) {
this.NotFull.L.Lock()
if this.MaxSize > 0 {
if uint32(this.List.Len()) == this.MaxSize {
this.NotFull.Wait()
}
}
this.List.PushBack(item)
this.UnfinishedTasks++
this.NotEmpty.Signal()
this.NotFull.L.Unlock()
}
func (this *Queue) Get() interface{} {
this.NotEmpty.L.Lock()
if this.List.Len() <= 0 {
this.NotEmpty.Wait()
}
item := this.List.Front()
this.List.Remove(item)
this.NotFull.Signal()
this.NotEmpty.L.Unlock()
return item.Value
}