summaryrefslogtreecommitdiff
path: root/src/mutex.cpp
blob: 2f15c8077d4159c1d899c91c1ff092d4194d716a (plain) (blame)
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
#include <mutex.h>
#include <exception.h>
#include <logger.h>

#include <cerrno>

namespace newsbeuter {

mutex::mutex() {
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
	pthread_mutex_init(&mtx, &attr);
}

mutex::~mutex() {
	pthread_mutex_destroy(&mtx);
	pthread_mutexattr_destroy(&attr);
}

void mutex::lock() {
	pthread_mutex_lock(&mtx);
}

void mutex::unlock() {
	pthread_mutex_unlock(&mtx);
}

bool mutex::trylock() {
	int rc = pthread_mutex_trylock(&mtx);
	if (rc != 0) {
		if (EBUSY == rc) {
			return false;
		} else {
			throw exception(rc);
		}
	} else {
		return true;
	}
}

scope_mutex::scope_mutex(mutex * m) : mtx(m) {
	if (mtx) {
		mtx->lock();
	}
}

scope_mutex::~scope_mutex() {
	if (mtx) {
		mtx->unlock();
	}
}

}