The OpenD Programming Language

Mutex

This class represents a general purpose, recursive mutex.

Implemented using pthread_mutex on Posix and CRITICAL_SECTION

on Windows.

Constructors

this
this()

Initializes a mutex object.

this
this(Object obj)

Initializes a mutex object and sets it as the monitor for obj.

Destructor

A destructor is present on this object, but not explicitly documented in the source.

Members

Functions

lock
void lock()
lock_nothrow
void lock_nothrow()

If this lock is not already held by the caller, the lock is acquired, then the internal counter is incremented by one.

tryLock
bool tryLock()
tryLock_nothrow
bool tryLock_nothrow()

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.

unlock
void unlock()
unlock_nothrow
void unlock_nothrow()

Decrements the internal lock count by one. If this brings the count to zero, the lock is released.

Examples

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);

Meta