Debian Codegraph @

libphobos/libdruntime/core/sync/mutex.d

raw
1 /**
2 * The mutex module provides a primitive for maintaining mutually exclusive
3 * access.
4 *
5 * Copyright: Copyright Sean Kelly 2005 - 2009.
6 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Authors: Sean Kelly
8 * Source: $(DRUNTIMESRC core/sync/_mutex.d)
9 */
10
11 /* Copyright Sean Kelly 2005 - 2009.
12 * Distributed under the Boost Software License, Version 1.0.
13 * (See accompanying file LICENSE or copy at
14 * http://www.boost.org/LICENSE_1_0.txt)
15 */
16 module core.sync.mutex;
17
18
19 public import core.sync.exception;
20
21 version (Windows)
22 {
23 import core.sys.windows.winbase /+: CRITICAL_SECTION, DeleteCriticalSection,
24 EnterCriticalSection, InitializeCriticalSection, LeaveCriticalSection,
25 TryEnterCriticalSection+/;
26 }
27 else version (Posix)
28 {
29 import core.sys.posix.pthread : pthread_mutex_destroy, pthread_mutex_init, pthread_mutex_lock,
30 PTHREAD_MUTEX_RECURSIVE, pthread_mutex_trylock, pthread_mutex_unlock, pthread_mutexattr_destroy,
31 pthread_mutexattr_init, pthread_mutexattr_settype;
32 import core.sys.posix.sys.types : pthread_mutex_t, pthread_mutexattr_t;
33 }
34 else
35 {
36 static assert(false, "Platform not supported");
37 }
38
39 ////////////////////////////////////////////////////////////////////////////////
40 // Mutex
41 //
42 // void lock();
43 // void unlock();
44 // bool tryLock();
45 ////////////////////////////////////////////////////////////////////////////////
46
47
48 /**
49 * This class represents a general purpose, recursive mutex.
50 *
51 * Implemented using `pthread_mutex` on Posix and `CRITICAL_SECTION`
52 * on Windows.
53 */
54 class Mutex :
55 Object.Monitor
56 {
57 ////////////////////////////////////////////////////////////////////////////
58 // Initialization
59 ////////////////////////////////////////////////////////////////////////////
60
61
62 /**
63 * Initializes a mutex object.
64 *
65 */
66 this() @trusted nothrow @nogc
67 {
68 this(true);
69 }
70
71 /// ditto
72 this() shared @trusted nothrow @nogc
73 {
74 this(true);
75 }
76
77 // Undocumented, useful only in Mutex.this().
78 private this(this Q)(bool _unused_) @trusted nothrow @nogc
79 if (is(Q == Mutex) || is(Q == shared Mutex))
80 {
81 version (Windows)
82 {
83 InitializeCriticalSection(cast(CRITICAL_SECTION*) &m_hndl);
84 }
85 else version (Posix)
86 {
87 import core.internal.abort : abort;
88 pthread_mutexattr_t attr = void;
89
90 !pthread_mutexattr_init(&attr) ||
91 abort("Error: pthread_mutexattr_init failed.");
92
93 scope (exit) !pthread_mutexattr_destroy(&attr) ||
94 abort("Error: pthread_mutexattr_destroy failed.");
95
96 !pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) ||
97 abort("Error: pthread_mutexattr_settype failed.");
98
99 !pthread_mutex_init(cast(pthread_mutex_t*) &m_hndl, &attr) ||
100 abort("Error: pthread_mutex_init failed.");
101 }
102
103 m_proxy.link = this;
104 this.__monitor = cast(void*) &m_proxy;
105 }
106
107
108 /**
109 * Initializes a mutex object and sets it as the monitor for `obj`.
110 *
111 * In:
112 * `obj` must not already have a monitor.
113 */
114 this(Object obj) @trusted nothrow @nogc
115 {
116 this(obj, true);
117 }
118
119 /// ditto
120 this(Object obj) shared @trusted nothrow @nogc
121 {
122 this(obj, true);
123 }
124
125 // Undocumented, useful only in Mutex.this(Object).
126 private this(this Q)(Object obj, bool _unused_) @trusted nothrow @nogc
127 if (is(Q == Mutex) || is(Q == shared Mutex))
128 in
129 {
130 assert(obj !is null,
131 "The provided object must not be null.");
132 assert(obj.__monitor is null,
133 "The provided object has a monitor already set!");
134 }
135 do
136 {
137 this();
138 obj.__monitor = cast(void*) &m_proxy;
139 }
140
141
142 ~this() @trusted nothrow @nogc
143 {
144 version (Windows)
145 {
146 DeleteCriticalSection(&m_hndl);
147 }
148 else version (Posix)
149 {
150 import core.internal.abort : abort;
151 !pthread_mutex_destroy(&m_hndl) ||
152 abort("Error: pthread_mutex_destroy failed.");
153 }
154 this.__monitor = null;
155 }
156
157
158 ////////////////////////////////////////////////////////////////////////////
159 // General Actions
160 ////////////////////////////////////////////////////////////////////////////
161
162
163 /**
164 * If this lock is not already held by the caller, the lock is acquired,
165 * then the internal counter is incremented by one.
166 *
167 * Note:
168 * `Mutex.lock` does not throw, but a class derived from Mutex can throw.
169 * Use `lock_nothrow` in `nothrow @nogc` code.
170 */
171 @trusted void lock()
172 {
173 lock_nothrow();
174 }
175
176 /// ditto
177 @trusted void lock() shared
178 {
179 lock_nothrow();
180 }
181
182 /// ditto
183 final void lock_nothrow(this Q)() nothrow @trusted @nogc
184 if (is(Q == Mutex) || is(Q == shared Mutex))
185 {
186 version (Windows)
187 {
188 EnterCriticalSection(&m_hndl);
189 }
190 else version (Posix)
191 {
192 if (pthread_mutex_lock(&m_hndl) == 0)
193 return;
194
195 SyncError syncErr = cast(SyncError) __traits(initSymbol, SyncError).ptr;
196 syncErr.msg = "Unable to lock mutex.";
197 throw syncErr;
198 }
199 }
200
201 /**
202 * Decrements the internal lock count by one. If this brings the count to
203 * zero, the lock is released.
204 *
205 * Note:
206 * `Mutex.unlock` does not throw, but a class derived from Mutex can throw.
207 * Use `unlock_nothrow` in `nothrow @nogc` code.
208 */
209 @trusted void unlock()
210 {
211 unlock_nothrow();
212 }
213
214 /// ditto
215 @trusted void unlock() shared
216 {
217 unlock_nothrow();
218 }
219
220 /// ditto
221 final void unlock_nothrow(this Q)() nothrow @trusted @nogc
222 if (is(Q == Mutex) || is(Q == shared Mutex))
223 {
224 version (Windows)
225 {
226 LeaveCriticalSection(&m_hndl);
227 }
228 else version (Posix)
229 {
230 if (pthread_mutex_unlock(&m_hndl) == 0)
231 return;
232
233 SyncError syncErr = cast(SyncError) __traits(initSymbol, SyncError).ptr;
234 syncErr.msg = "Unable to unlock mutex.";
235 throw syncErr;
236 }
237 }
238
239 /**
240 * If the lock is held by another caller, the method returns. Otherwise,
241 * the lock is acquired if it is not already held, and then the internal
242 * counter is incremented by one.
243 *
244 * Returns:
245 * true if the lock was acquired and false if not.
246 *
247 * Note:
248 * `Mutex.tryLock` does not throw, but a class derived from Mutex can throw.
249 * Use `tryLock_nothrow` in `nothrow @nogc` code.
250 */
251 bool tryLock() @trusted
252 {
253 return tryLock_nothrow();
254 }
255
256 /// ditto
257 bool tryLock() shared @trusted
258 {
259 return tryLock_nothrow();
260 }
261
262 /// ditto
263 final bool tryLock_nothrow(this Q)() nothrow @trusted @nogc
264 if (is(Q == Mutex) || is(Q == shared Mutex))
265 {
266 version (Windows)
267 {
268 return TryEnterCriticalSection(&m_hndl) != 0;
269 }
270 else version (Posix)
271 {
272 return pthread_mutex_trylock(&m_hndl) == 0;
273 }
274 }
275
276
277 private:
278 version (Windows)
279 {
280 CRITICAL_SECTION m_hndl;
281 }
282 else version (Posix)
283 {
284 pthread_mutex_t m_hndl;
285 }
286
287 struct MonitorProxy
288 {
289 Object.Monitor link;
290 }
291
292 MonitorProxy m_proxy;
293
294
295 package:
296 version (Posix)
297 {
298 pthread_mutex_t* handleAddr() @nogc
299 {
300 return &m_hndl;
301 }
302 }
303 }
304
305 ///
306 /* @safe nothrow -> see druntime PR 1726 */
307 // Test regular usage.
308 unittest
309 {
310 import core.thread : Thread;
311
312 class Resource
313 {
314 Mutex mtx;
315 int cargo;
316
317 this() shared @safe nothrow
318 {
319 mtx = new shared Mutex();
320 cargo = 42;
321 }
322
323 void useResource() shared @trusted nothrow @nogc
324 {
325 mtx.lock_nothrow();
326 (cast() cargo) += 1;
327 mtx.unlock_nothrow();
328 }
329 }
330
331 shared Resource res = new shared Resource();
332
333 auto otherThread = new Thread(
334 {
335 foreach (i; 0 .. 10000)
336 res.useResource();
337 }).start();
338
339 foreach (i; 0 .. 10000)
340 res.useResource();
341
342 otherThread.join();
343
344 assert (res.cargo == 20042);
345 }
346
347 // Test @nogc usage.
348 @system @nogc nothrow unittest
349 {
350 import core.lifetime : emplace;
351 import core.stdc.stdlib : free, malloc;
352
353 auto mtx = cast(shared Mutex) malloc(__traits(classInstanceSize, Mutex));
354 emplace(mtx);
355
356 mtx.lock_nothrow();
357
358 { // test recursive locking
359 mtx.tryLock_nothrow();
360 mtx.unlock_nothrow();
361 }
362
363 mtx.unlock_nothrow();
364
365 // In general destorying classes like this is not
366 // safe, but since we know that the only base class
367 // of Mutex is Object and it doesn't have a dtor
368 // we can simply call the non-virtual __dtor() here.
369
370 // Ok to cast away shared because destruction
371 // should happen only from a single thread.
372 (cast(Mutex) mtx).__dtor();
373
374 // Verify that the underlying implementation has been destroyed by checking
375 // that locking is not possible. This assumes that the underlying
376 // implementation is well behaved and makes the object non-lockable upon
377 // destruction. The Bionic, DragonFly, Musl, and Solaris C runtimes don't
378 // appear to do so, so skip this test.
379 version (CRuntime_Bionic) {} else
380 version (CRuntime_Musl) {} else
381 version (DragonFlyBSD) {} else
382 version (Solaris) {} else
383 assert(!mtx.tryLock_nothrow());
384
385 free(cast(void*) mtx);
386 }
387
388 // Test single-thread (non-shared) use.
389 unittest
390 {
391 Mutex m = new Mutex();
392
393 m.lock();
394
395 m.tryLock();
396 m.unlock();
397
398 m.unlock();
399 }
400
401 unittest
402 {
403 import core.thread;
404
405 auto mutex = new Mutex;
406 int numThreads = 10;
407 int numTries = 1000;
408 int lockCount = 0;
409
410 void testFn()
411 {
412 for (int i = 0; i < numTries; ++i)
413 {
414 synchronized (mutex)
415 {
416 ++lockCount;
417 }
418 }
419 }
420
421 auto group = new ThreadGroup;
422
423 for (int i = 0; i < numThreads; ++i)
424 group.create(&testFn);
425
426 group.joinAll();
427 assert(lockCount == numThreads * numTries);
428 }