File: queue.h

package info (click to toggle)
powder 118%2Bdfsg1-3
  • links: PTS, VCS
  • area: non-free
  • in suites: bookworm, bullseye, sid, trixie
  • size: 10,528 kB
  • sloc: cpp: 55,308; java: 824; makefile: 541; sh: 260; objc: 245; ansic: 107; xml: 55; csh: 54
file content (95 lines) | stat: -rw-r--r-- 1,743 bytes parent folder | download | duplicates (4)
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
/*
 * Licensed under BSD license.  See LICENCE.TXT  
 *
 * Produced by:	Jeff Lait
 *
 *      	7DRL Development
 *
 * NAME:        queue.h ( Letter Hunt Library, C++ )
 *
 * COMMENTS:
 *	Implements a simple queue.
 *	Is threadsafe.  Has the ability to block until an item
 * 	is available.
 */


#ifndef __queue_h__
#define __queue_h__

#include "ptrlist.h"
#include "thread.h"

template <typename PTR>
class QUEUE
{
public:
    QUEUE() { myMaxSize = 0; }
    explicit QUEUE(int maxsize) { myMaxSize = maxsize; }
    ~QUEUE() {}

    // Because we are multithreaded, this is not meant to remain valid
    // outside of a lock.
    bool		isEmpty() const
    {
	return myList.entries() == 0;
    }

    // Non-blocking empty of the queue, no freeing of the results.
    // May not be empty afterward due to multithreading!
    void		flush() 
    {
	PTR		item;
	while (remove(item));
    }

    // Removes item, returns false if failed because queue is empty.
    bool		remove(PTR &item)
    {
	AUTOLOCK	l(myLock);

	if (isEmpty())
	    return false;
	item = myList.removeFirst();
	return true;
    }

    // Blocks till an element is ready.
    PTR			waitAndRemove()
    {
	AUTOLOCK	l(myLock);
	PTR		result;

	while (!remove(result))
	{
	    myCond.wait(myLock);
	}
	return result;
    }

    bool		append(const PTR &item)
    {
	AUTOLOCK	l(myLock);

	// Fail to append if we are full.
	if (myMaxSize && myList.entries() >= myMaxSize)
	    return false;

	myList.append(item);
	myCond.trigger();

	return true;
    }

private:
    // Copying locks scares me.
    QUEUE(const QUEUE<PTR> &ref) {}
    QUEUE<PTR> &operator=(const QUEUE<PTR> &ref) {}

    PTRLIST<PTR>	myList;
    LOCK		myLock;
    CONDITION		myCond;
    int			myMaxSize;
};

#endif