0
|
1 module dreactor.util.ThreadSafeQueue;
|
|
2
|
|
3 import tango.util.collection.CircularSeq;
|
3
|
4 import tango.core.Atomic;
|
0
|
5
|
3
|
6 import tango.util.log.Log;
|
|
7 import tango.util.log.Config;
|
0
|
8 /******************************************************************************
|
|
9
|
|
10 ThreadSafeQueue
|
|
11 Queue that is probably thread safe. It acts as a job queue, in that
|
|
12 you can push or pop off of the queue. Or you can processAll, which will
|
|
13 apply a delegate to each item, then clear the list.
|
|
14
|
|
15 ******************************************************************************/
|
|
16 class ThreadSafeQueue(TYPE)
|
|
17 {
|
|
18 public
|
|
19 this(int maxsz = 1000)
|
|
20 {
|
3
|
21 list_ = new CircularSeq!(TYPE);
|
|
22 maxsize_ = maxsz;
|
|
23 size_ = 0;
|
|
24 log = Log.lookup("dreactor.util.ThreadSafeQueue");
|
0
|
25 }
|
|
26
|
|
27 synchronized bool pop(ref TYPE t)
|
|
28 {
|
3
|
29 if (size_ > 0)
|
0
|
30 {
|
3
|
31 t = list_.head();
|
|
32 list_.removeHead();
|
|
33 size_--;
|
0
|
34 return true;
|
|
35 }
|
|
36 else
|
|
37 return false;
|
|
38 }
|
|
39
|
|
40 synchronized bool push(TYPE t)
|
|
41 {
|
3
|
42 if (size_ < maxsize_)
|
0
|
43 {
|
3
|
44 list_.append(t);
|
|
45 size_++;
|
0
|
46 return true;
|
|
47 }
|
|
48 else
|
|
49 return false;
|
|
50 }
|
|
51
|
|
52 synchronized int size()
|
|
53 {
|
3
|
54 return size_;
|
0
|
55 }
|
|
56
|
3
|
57 synchronized int processAll(int delegate(ref TYPE value) dg)
|
0
|
58 {
|
3
|
59 if (0 >= size_)
|
|
60 return 0;
|
|
61
|
0
|
62 int count = 0;
|
3
|
63 foreach(TYPE t; list_)
|
0
|
64 {
|
|
65 if (dg(t) < 0)
|
|
66 break;
|
|
67 ++count;
|
|
68 }
|
3
|
69 if (count == size_)
|
|
70 {
|
0
|
71 clear_();
|
3
|
72 size_ = 0;
|
|
73 }
|
0
|
74 else
|
3
|
75 {
|
|
76 list_.removeRange(0, count);
|
|
77 size_ -= count;
|
|
78 }
|
0
|
79 return count;
|
|
80 }
|
|
81
|
|
82 synchronized void clear()
|
|
83 {
|
|
84 clear_();
|
|
85 }
|
|
86
|
|
87 private
|
|
88
|
|
89 void clear_()
|
|
90 {
|
3
|
91 list_.clear();
|
|
92 size_ = 0 ;
|
0
|
93 }
|
|
94
|
3
|
95 int maxsize_;
|
|
96 int size_;
|
|
97 Logger log;
|
|
98 CircularSeq!(TYPE) list_;
|
0
|
99 }
|