~evan-nelson/armagetronad/armagetronad+pcm

« back to all changes in this revision

Viewing changes to src/tools/pthread-binding.h

Attempting to create a timeout for PLAYER_CENTER_MESSAGE.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#include <deque>
2
 
#include <pthread.h>
3
 
#include <stdexcept>
4
 
 
5
 
class tPThreadMutex
6
 
{
7
 
private:
8
 
    pthread_mutex_t mutex;
9
 
public:
10
 
    tPThreadMutex() {
11
 
        // TODO: error checking
12
 
        pthread_mutex_init(&mutex, NULL);
13
 
    }
14
 
    void acquire() {
15
 
        pthread_mutex_lock(&mutex);
16
 
    };
17
 
    void release() {
18
 
        pthread_mutex_unlock(&mutex);
19
 
    };
20
 
};
21
 
 
22
 
class tPThreadRecursiveMutex
23
 
 : public tPThreadMutex
24
 
{
25
 
private:
26
 
    pthread_mutex_t mutex;
27
 
public:
28
 
    tPThreadRecursiveMutex() {
29
 
        // TODO: error checking
30
 
        pthread_mutexattr_t mta;
31
 
        
32
 
        pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE);
33
 
        pthread_mutex_init(&mutex, &mta);
34
 
    }
35
 
};
36
 
 
37
 
template <class T>
38
 
class tPThreadGuard
39
 
{
40
 
private:
41
 
    T*mutex;
42
 
public:
43
 
    tPThreadGuard(T*m) {
44
 
        mutex = m;
45
 
        mutex->acquire();
46
 
    };
47
 
    ~tPThreadGuard() {
48
 
        mutex->release();
49
 
    };
50
 
};
51
 
 
52
 
template <class T, class MutexT>
53
 
class tPThreadQueue
54
 
{
55
 
    MutexT mutex;
56
 
    std::deque<T> q;
57
 
public:
58
 
    virtual void add(const T& item) {
59
 
        tPThreadGuard<MutexT> mL(&mutex);
60
 
        
61
 
        q.push_back(item);
62
 
    }
63
 
    
64
 
    virtual size_t size() {
65
 
        tPThreadGuard<MutexT> mL(&mutex);
66
 
        
67
 
        return q.size();
68
 
    }
69
 
    
70
 
    virtual T next() {
71
 
        tPThreadGuard<MutexT> mL(&mutex);
72
 
 
73
 
        if(q.size() == 0)
74
 
            // TODO: throw a specific exception?
75
 
            throw std::exception();
76
 
 
77
 
        T item = q.front();
78
 
        q.pop_front();
79
 
        
80
 
        return item;
81
 
    }
82
 
};