summaryrefslogtreecommitdiff
path: root/src/atomic.h
blob: e0e735d8f43cdc5cbd3d6f49cb2b2d2e5d20cbc3 (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
#ifndef _ATOMIC_H_
#define _ATOMIC_H_

#include <stdlib.h>
#include <pthread.h>
#include <util.h>

typedef int refcnt;

static inline void refcnt_inc(refcnt *cnt)
{
	__sync_add_and_fetch(cnt, 1);
}

static inline refcnt refcnt_dec(refcnt *cnt)
{
	return __sync_sub_and_fetch(cnt, 1);
}


typedef pthread_mutex_t lock;

static inline void lock_init(lock *l)
{
	pthread_mutex_init(l, NULL);
}

static inline void lock_acquire(lock *l)
{
	int ret = pthread_mutex_lock(l);
	if (ret < 0) {
		switch (ret) {
		case EINVAL:
			pr_err("invalid mutex\n");
			exit(1);
		case EDEADLK:
			pr_err("a deadlock would occur\n");
			exit(1);
		}
	}
}

static inline void lock_release(lock *l)
{
	int ret = pthread_mutex_unlock(l);
	if (ret < 0) {
		switch (ret) {
		case EINVAL:
			pr_err("invalid mutex\n");
			exit(1);
		case EPERM:
			pr_err("this thread does not hold this mutex\n");
			exit(1);
		}
	}
}

#endif /* _ATOMIC_H_ */