summaryrefslogtreecommitdiffstats
path: root/src/threads/mutex.h
blob: 9970e088290495b160630387d4ab300e4683fa59 (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
/*
    Copyright (C) 2005-2009  Michel de Boer <michel@twinklephone.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#ifndef _H_MUTEX
#define _H_MUTEX

#include <errno.h>
#include <pthread.h>

/**
 * @file
 * Mutex operations
 */

class t_mutex {
protected:
	pthread_mutex_t		mutex;

public:
	t_mutex();

	// Throws a string exception (error message) when failing.
	t_mutex(bool recursive);

	virtual ~t_mutex();

	// These methods throw a string exception when the operation
	// fails.
	virtual void lock(void);

	// Returns:
	// 0 - success
	// EBUSY - already locked
	// For other errors a string exception is thrown
	virtual int trylock(void);
	virtual void unlock(void);
};

class t_recursive_mutex : public t_mutex {
public:
	t_recursive_mutex();
	~t_recursive_mutex();
};


/** 
 * Guard pattern for a mutex .
 * The constructor of a guard locks a mutex and the destructor
 * unlocks it. This way a guard object can be created at entrance
 * of a function. Then at exit, the mutex is automically unlocked
 * as the guard object goes out of scope.
 */
class t_mutex_guard {
private:
	/** The guarding mutex. */
	t_mutex		&mutex_;
	
public:
	/**
	 * The constructor will lock the mutex.
	 * @param mutex [in] Mutex to lock.
	 */
	t_mutex_guard(t_mutex &mutex);
	
	/**
	 * The destructor will unlock the mutex.
	 */
	~t_mutex_guard();
};

#endif