英語版
このページの英語版を見る

core.sync.mutex

ミューテックス・モジュールは、相互排他的なアクセスを維持するためのプリミティブを提供する。 プリミティブを提供する。
Authors:
Sean Kelly
class Mutex: object.Object.Monitor;
このクラスは汎用の再帰的ミューテックスを表す。
Posixではpthread_mutex 、WindowsではCRITICAL_SECTION で実装されている。
Examples:
import core.thread : Thread;

class Resource
{
    Mutex mtx;
    int cargo;

    this() shared @safe nothrow
    {
        mtx = new shared Mutex();
        cargo = 42;
    }

    void useResource() shared @trusted 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);
nothrow @nogc @trusted this();

shared nothrow @nogc @trusted this();
ミューテックス・オブジェクトを初期化する。
nothrow @nogc @trusted this(Object obj);

shared nothrow @nogc @trusted this(Object obj);
ミューテックス・オブジェクトを初期化し、それを obj.

のモニターとして設定する。 objのモニターとして設定する。

@trusted void lock();

shared @trusted void lock();

final nothrow @nogc @trusted void lock_nothrow(this Q)()
if (is(Q == Mutex) || is(Q == shared(Mutex)));
このロックが呼び出し元によってまだ保持されていない場合、ロックが取得される、 その後、内部カウンタが1つインクリメントされる。

注釈:」が必要である。 Mutex.lockはスローしないが、Mutexから派生したクラスはスローできる。 使用方法 lock_nothrownothrow @nogc

@trusted void unlock();

shared @trusted void unlock();

final nothrow @nogc @trusted void unlock_nothrow(this Q)()
if (is(Q == Mutex) || is(Q == shared(Mutex)));
内部ロックカウントを1つ減らす。 これでカウントがゼロになると、ロックは解放される。 カウントがゼロになると、ロックは解放される。

注釈: ロックを解除する。 Mutex.unlockはスローしないが、Mutexから派生したクラスはスローできる。 使用方法 unlock_nothrownothrow @nogc を使う。

@trusted bool tryLock();

shared @trusted bool tryLock();

final nothrow @nogc @trusted bool tryLock_nothrow(this Q)()
if (is(Q == Mutex) || is(Q == shared(Mutex)));
ロックが他の呼び出し元によって保持されている場合、メソッドは戻る。 そうでなければ を取得し、内部カウンタを1つインクリメントする。 カウンタが1つインクリメントされる。
Returns:
ロックが獲得された場合はtrue、獲得されなかった場合はfalseが返される。

注釈: ロックを取得した。 Mutex.tryLockはスローしないが、Mutexから派生したクラスはスローできる。 使用方法 tryLock_nothrownothrow @nogc