about summary refs log tree commit diff
path: root/src/base/tl/threading.h
blob: 66751ec4c7fda80361e376f7b5938dea631083b3 (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

#pragma once

#include "../system.h"

inline unsigned atomic_inc(volatile unsigned *pValue)
{
	return __sync_fetch_and_add(pValue, 1);
}

inline unsigned atomic_dec(volatile unsigned *pValue)
{
	return __sync_fetch_and_add(pValue, -1);
}

inline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value)
{
	return __sync_val_compare_and_swap(pValue, comperand, value);
}

inline void sync_barrier()
{
	__sync_synchronize();
}

#include <semaphore.h>
typedef sem_t SEMAPHORE;
inline void semaphore_init(SEMAPHORE *sem) { sem_init(sem, 0, 0); }
inline void semaphore_wait(SEMAPHORE *sem) { sem_wait(sem); }
inline void semaphore_signal(SEMAPHORE *sem) { sem_post(sem); }
inline void semaphore_destroy(SEMAPHORE *sem) { sem_destroy(sem); }

class semaphore
{
	SEMAPHORE sem;
public:
	semaphore() { semaphore_init(&sem); }
	~semaphore() { semaphore_destroy(&sem); }
	void wait() { semaphore_wait(&sem); }
	void signal() { semaphore_signal(&sem); }
};

class lock
{
	friend class scope_lock;

	LOCK var;

	void take() { lock_wait(var); }
	void release() { lock_release(var); }

public:
	lock()
	{
		var = lock_create();
	}

	~lock()
	{
		lock_destroy(var);
	}
};

class scope_lock
{
	lock *var;
public:
	scope_lock(lock *l)
	{
		var = l;
		var->take();
	}

	~scope_lock()
	{
		var->release();
	}
};