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