summaryrefslogtreecommitdiff
path: root/fifo.h
blob: 87c979b6a89e9b7a22286fc87f574dd947a18ac7 (plain)
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
/*
 * gamepad.c: A plugin for the Video Disk Recorder
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id$
 */
#ifndef FIFO_H
#define FIFO_H

#include <vdr/tools.h>

template<class T> class cFifo {
private:
    cMutex mutex;
    cCondWait wake;
    T *buffer;
    int readp;
    int writep;
    const int length;
    int size;

public:
    cFifo(int _length) : readp(0), writep(0), length(_length), size(0)
    {
        buffer = (T*)malloc(length * sizeof(T));
        if (!buffer)
        {
            esyslog("ERROR: out of memory - abort!");
            abort();
        }
    }

    // non blocking write, returns true on success
    bool put(T *item)
    {
        bool success = false;
        mutex.Lock();
        if (size < length)
        {
            buffer[writep] = *item;
            size++;
            writep = (writep + 1) % length;
            success = true;
            wake.Signal();
        }
        mutex.Unlock();
        return success;
    }

    // returns a pointer to the head element
    // to delete it from the fifo use remove
    T* read(int timeoutMs)
    {
        bool wait = false;
        T* ret = NULL;
        mutex.Lock();
        if (size == 0) {
            wait = true;
        }
        mutex.Unlock();
        if (wait)
        {
            wake.Wait(timeoutMs);
        }
        mutex.Lock();
        if (size != 0)
        {
            ret = &(buffer[readp]);
        }
        mutex.Unlock();
        return ret;
    }

    void remove() {
        mutex.Lock();
        if (size >= 0)
        {
            readp = (readp + 1) % length;
            size--;
        }
        mutex.Unlock();
    }
};

#endif