xref: /haiku/src/kits/support/Locker.cpp (revision 425b1199b0cb2116ac84cd286d29569e62d86774)
1 /*
2  * Copyright (c) 2001-2005, Haiku, Inc.
3  * Distributed under the terms of the MIT license.
4  *
5  * Author:	Erik Jaesler <erik@cgsoftware.com>
6  */
7 
8 /**	Semaphore-type class for thread safety */
9 
10 
11 #include <OS.h>
12 #include <Locker.h>
13 #include <SupportDefs.h>
14 
15 #include "support_kit_config.h"
16 
17 //
18 // Data Member Documentation:
19 //
20 // The "fBenaphoreCount" member is set to 1 if the BLocker style is
21 // semaphore.  If the style is benaphore, it is initialized to 0 and
22 // is incremented atomically when it is acquired, decremented when it
23 // is released.  By setting the benaphore count to 1 when the style is
24 // semaphore, the benaphore effectively becomes a semaphore.  I was able
25 // to determine this is what Be's implementation does by testing the
26 // result of the CountLockRequests() member.
27 //
28 // The "fSemaphoreID" member holds the sem_id returned from create_sem()
29 // when the BLocker is constructed.  It is used to acquire and release
30 // the lock regardless of the lock style (semaphore or benaphore).
31 //
32 // The "fLockOwner" member holds the thread_id of the thread which
33 // currently holds the lock.  If no thread holds the lock, it is set to
34 // B_ERROR.
35 //
36 // The "fRecursiveCount" member holds a count of the number of times the
37 // thread holding the lock has acquired the lock without a matching unlock.
38 // It is basically the number of times the thread must call Unlock() before
39 // the lock can be acquired by a different thread.
40 //
41 
42 
43 //
44 // Constructors:
45 //
46 // All constructors just pass their arguments to InitLocker().  Note that
47 // the default for "name" is "some BLocker" and "benaphore_style" is true.
48 //
49 
50 BLocker::BLocker()
51 {
52 	InitLocker(NULL, true);
53 }
54 
55 
56 BLocker::BLocker(const char *name)
57 {
58 	InitLocker(name, true);
59 }
60 
61 
62 BLocker::BLocker(bool benaphoreStyle)
63 {
64 	InitLocker(NULL, benaphoreStyle);
65 }
66 
67 
68 BLocker::BLocker(const char *name, bool benaphoreStyle)
69 {
70 	InitLocker(name, benaphoreStyle);
71 }
72 
73 
74 //
75 //	This constructor is not documented.  The final argument is ignored for
76 //	now.  In Be's headers, its called "for_IPC".  DO NOT USE THIS
77 //	CONSTRUCTOR!
78 //
79 BLocker::BLocker(const char *name, bool benaphoreStyle,
80 	bool)
81 {
82 	InitLocker(name, benaphoreStyle);
83 }
84 
85 
86 //
87 // The destructor just deletes the semaphore.  By deleting the semaphore,
88 // any threads waiting to acquire the BLocker will be unblocked.
89 //
90 BLocker::~BLocker()
91 {
92 	delete_sem(fSemaphoreID);
93 }
94 
95 
96 bool
97 BLocker::Lock(void)
98 {
99 	status_t result;
100     return AcquireLock(B_INFINITE_TIMEOUT, &result);
101 }
102 
103 
104 status_t
105 BLocker::LockWithTimeout(bigtime_t timeout)
106 {
107     status_t result;
108 
109 	AcquireLock(timeout, &result);
110     return result;
111 }
112 
113 
114 
115 void
116 BLocker::Unlock(void)
117 {
118 	// If the thread currently holds the lockdecrement
119 	if (IsLocked()) {
120 		// Decrement the number of outstanding locks this thread holds
121 		// on this BLocker.
122 		fRecursiveCount--;
123 
124 		// If the recursive count is now at 0, that means the BLocker has
125 		// been released by the thread.
126 		if (fRecursiveCount == 0) {
127 			// The BLocker is no longer owned by any thread.
128 			fLockOwner = B_ERROR;
129 
130     		// Decrement the benaphore count and store the undecremented
131     		// value in oldBenaphoreCount.
132 			int32 oldBenaphoreCount = atomic_add(&fBenaphoreCount, -1);
133 
134 			// If the oldBenaphoreCount is greater than 1, then there is
135 			// at lease one thread waiting for the lock in the case of a
136 			// benaphore.
137    		    if (oldBenaphoreCount > 1) {
138  				// Since there are threads waiting for the lock, it must
139  				// be released.  Note, the old benaphore count will always be
140  				// greater than 1 for a semaphore so the release is always done.
141     			release_sem(fSemaphoreID);
142 	    	}
143 	    }
144     }
145 }
146 
147 
148 thread_id
149 BLocker::LockingThread(void) const
150 {
151     return fLockOwner;
152 }
153 
154 
155 bool
156 BLocker::IsLocked(void) const
157 {
158 	// This member returns true if the calling thread holds the lock.
159 	// The easiest way to determine this is to compare the result of
160 	// find_thread() to the fLockOwner.
161     return find_thread(NULL) == fLockOwner;
162 }
163 
164 
165 int32
166 BLocker::CountLocks(void) const
167 {
168     return fRecursiveCount;
169 }
170 
171 
172 int32
173 BLocker::CountLockRequests(void) const
174 {
175     return fBenaphoreCount;
176 }
177 
178 
179 sem_id
180 BLocker::Sem(void) const
181 {
182     return fSemaphoreID;
183 }
184 
185 
186 void
187 BLocker::InitLocker(const char *name, bool benaphore)
188 {
189 	if (name == NULL)
190 		name = "some BLocker";
191 
192 	if (benaphore && !BLOCKER_ALWAYS_SEMAPHORE_STYLE) {
193 		// Because this is a benaphore, initialize the benaphore count and
194 		// create the semaphore.  Because this is a benaphore, the semaphore
195 		// count starts at 0 (ie acquired).
196 		fBenaphoreCount = 0;
197 		fSemaphoreID = create_sem(0, name);
198 	} else {
199 		// Because this is a semaphore, initialize the benaphore count to -1
200 		// and create the semaphore.  Because this is semaphore style, the
201 		// semaphore count starts at 1 so that one thread can acquire it and
202 		// the next thread to acquire it will block.
203 		fBenaphoreCount = 1;
204 		fSemaphoreID = create_sem(1, name);
205 	}
206 
207 	// The lock is currently not acquired so there is no owner.
208 	fLockOwner = B_ERROR;
209 
210 	// The lock is currently not acquired so the recursive count is zero.
211 	fRecursiveCount = 0;
212 }
213 
214 
215 bool
216 BLocker::AcquireLock(bigtime_t timeout, status_t *error)
217 {
218 	// By default, return no error.
219 	status_t status = B_OK;
220 
221 	// Only try to acquire the lock if the thread doesn't already own it.
222 	if (!IsLocked()) {
223 		// Increment the benaphore count and test to see if it was already greater
224 		// than 0.  If it is greater than 0, then some thread already has the
225 		// benaphore or the style is a semaphore.  Either way, we need to acquire
226 		// the semaphore in this case.
227 		int32 oldBenaphoreCount = atomic_add(&fBenaphoreCount, 1);
228 		if (oldBenaphoreCount > 0) {
229 			do {
230 				status = acquire_sem_etc(fSemaphoreID, 1, B_RELATIVE_TIMEOUT,
231 					timeout);
232 			} while (status == B_INTERRUPTED);
233 
234 			// Note, if the lock here does time out, the benaphore count
235 			// is not decremented.  By doing this, the benaphore count will
236 			// never go back to zero.  This means that the locking essentially
237 			// changes to semaphore style if this was a benaphore.
238 			//
239 			// Doing the decrement of the benaphore count when the acquisition
240 			// fails is a risky thing to do.  If you decrement the counter at
241 			// the same time the thread which holds the benaphore does an
242 			// Unlock(), there is serious risk of a race condition.
243 			//
244 			// If the Unlock() sees a positive count and releases the semaphore
245 			// and then the timed out thread decrements the count to 0, there
246 			// is no one to take the semaphore.  The next two threads will be
247 			// able to acquire the benaphore at the same time!  The first will
248 			// increment the counter and acquire the lock.  The second will
249 			// acquire the semaphore and therefore the lock.  Not good.
250 			//
251 			// This has been discussed on the becodetalk mailing list and
252 			// Trey from Be had this to say:
253 			//
254 			// I looked at the LockWithTimeout() code, and it does not have
255 			// _this_ (ie the race condition) problem.  It circumvents it by
256 			// NOT doing the atomic_add(&count, -1) if the semaphore
257 			// acquisition fails.  This means that if a
258 			// BLocker::LockWithTimeout() times out, all other Lock*() attempts
259 			// turn into guaranteed semaphore grabs, _with_ the overhead of a
260 			// (now) useless atomic_add().
261 			//
262 			// Given Trey's comments, it looks like Be took the same approach
263 			// I did.  The output of CountLockRequests() of Be's implementation
264 			// confirms Trey's comments also.
265 			//
266 			// Finally some thoughts for the future with this code:
267 			//   - If 2^31 timeouts occur on a 32-bit machine (ie today),
268 			//     the benaphore count will wrap to a negative number.  This
269 			//     would have unknown consequences on the ability of the BLocker
270 			//     to continue to function.
271 			//
272 		}
273 	}
274 
275 	// If the lock has successfully been acquired.
276 	if (status == B_OK) {
277 		// Set the lock owner to this thread and increment the recursive count
278 		// by one.  The recursive count is incremented because one more Unlock()
279 		// is now required to release the lock (ie, 0 => 1, 1 => 2 etc).
280 		fLockOwner = find_thread(NULL);
281 		fRecursiveCount++;
282 	}
283 
284 	if (error != NULL)
285 		*error = status;
286 
287 	// Return true if the lock has been acquired.
288 	return (status == B_OK);
289 }
290