Debian Codegraph @

queue.h

raw symbols SCIP
1 /*
2 * Licensed under BSD license. See LICENCE.TXT
3 *
4 * Produced by: Jeff Lait
5 *
6 * 7DRL Development
7 *
8 * NAME: queue.h ( Letter Hunt Library, C++ )
9 *
10 * COMMENTS:
11 * Implements a simple queue.
12 * Is threadsafe. Has the ability to block until an item
13 * is available.
14 */
15
16
17 #ifndef __queue_h__
18 #define __queue_h__
19
20 #include "ptrlist.h"
21 #include "thread.h"
22
23 template <typename PTR>
24 class QUEUE
25 {
26 public:
27 QUEUE() { myMaxSize = 0; }
28 explicit QUEUE(int maxsize) { myMaxSize = maxsize; }
29 ~QUEUE() {}
30
31 // Because we are multithreaded, this is not meant to remain valid
32 // outside of a lock.
33 bool isEmpty() const
34 {
35 return myList.entries() == 0;
36 }
37
38 // Non-blocking empty of the queue, no freeing of the results.
39 // May not be empty afterward due to multithreading!
40 void flush()
41 {
42 PTR item;
43 while (remove(item));
44 }
45
46 // Removes item, returns false if failed because queue is empty.
47 bool remove(PTR &item)
48 {
49 AUTOLOCK l(myLock);
50
51 if (isEmpty())
52 return false;
53 item = myList.removeFirst();
54 return true;
55 }
56
57 // Blocks till an element is ready.
58 PTR waitAndRemove()
59 {
60 AUTOLOCK l(myLock);
61 PTR result;
62
63 while (!remove(result))
64 {
65 myCond.wait(myLock);
66 }
67 return result;
68 }
69
70 bool append(const PTR &item)
71 {
72 AUTOLOCK l(myLock);
73
74 // Fail to append if we are full.
75 if (myMaxSize && myList.entries() >= myMaxSize)
76 return false;
77
78 myList.append(item);
79 myCond.trigger();
80
81 return true;
82 }
83
84 private:
85 // Copying locks scares me.
86 QUEUE(const QUEUE<PTR> &ref) {}
87 QUEUE<PTR> &operator=(const QUEUE<PTR> &ref) {}
88
89 PTRLIST<PTR> myList;
90 LOCK myLock;
91 CONDITION myCond;
92 int myMaxSize;
93 };
94
95 #endif