1/*
2 * Copyright 2006, Haiku, Inc. All Rights Reserved.
3 * Distributed under the terms of the MIT License.
4 *
5 * Authors:
6 *		Axel D��rfler, axeld@pinc-software.de
7 */
8#ifndef LOCK_H
9#define LOCK_H
10
11
12#include <OS.h>
13
14
15struct lock {
16	sem_id	sem;
17	int32	count;
18};
19
20
21static inline status_t
22init_lock(struct lock *lock, const char *name)
23{
24	lock->sem = create_sem(0, name);
25	lock->count = 0;
26
27	return lock->sem < B_OK ? lock->sem : B_OK;
28}
29
30
31static inline void
32uninit_lock(struct lock *lock)
33{
34	delete_sem(lock->sem);
35}
36
37
38static inline status_t
39acquire_lock(struct lock *lock)
40{
41	if (atomic_add(&lock->count, 1) > 0)
42		return acquire_sem(lock->sem);
43
44	return B_OK;
45}
46
47
48static inline status_t
49release_lock(struct lock *lock)
50{
51	if (atomic_add(&lock->count, -1) > 1)
52		return release_sem(lock->sem);
53
54	return B_OK;
55}
56
57
58class Autolock {
59	public:
60		Autolock(struct lock &lock)
61			:
62			fLock(&lock)
63		{
64			fStatus = acquire_lock(fLock);
65		}
66
67		~Autolock()
68		{
69			if (fStatus == B_OK)
70				release_lock(fLock);
71		}
72
73		bool
74		IsLocked() const
75		{
76			return fStatus == B_OK;
77		}
78
79	private:
80		status_t	fStatus;
81		struct lock	*fLock;
82};
83
84#endif	/* LOCK_H */
85