xref: /haiku/headers/private/graphics/intel_extreme/lock.h (revision 7b3e89c0944ae1efa9a8fc66c7303874b7a344b2)
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 
15 struct lock {
16 	sem_id	sem;
17 	int32	count;
18 };
19 
20 
21 static inline status_t
22 init_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 
31 static inline void
32 uninit_lock(struct lock *lock)
33 {
34 	delete_sem(lock->sem);
35 }
36 
37 
38 static inline status_t
39 acquire_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 
48 static inline status_t
49 release_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 
58 class 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