Mutex

Mutex structure. Uses CRITICAL_SECTION under Windows, pthread_mutex_t under Posix

Members

Functions

destroy
int destroy()

Destroy the mutex

init
int init()

Initialize the mutex

lock
int lock()

Enter critical section. If the mutex is already locked, block the thread until it becomes available

tryLock
int tryLock()

Try to enter critical section. Return immediately if the mutex is already locked

unlock
int unlock()

Leave critical section

Variables

_mutex
CRITICAL_SECTION _mutex;
Undocumented in source.
_mutex
pthread_mutex_t _mutex;
Undocumented in source.

Examples

import dlib.core.memory;
import dlib.core.thread;

int x = 0;
Mutex mutex;
mutex.init();

void add()
{
    mutex.lock();
    int local = x;
    local = local + 1;
    x = local;
    mutex.unlock();
}

void sub()
{
    mutex.lock();
    int local = x;
    local = local - 1;
    x = local;
    mutex.unlock();
}

Thread[100] threads;

foreach(i; 0..threads.length/2)
{
    threads[i] = New!Thread(&add);
    threads[i].start();
}

foreach(i; threads.length/2..threads.length)
{
    threads[i] = New!Thread(&sub);
    threads[i].start();
}

foreach(t; threads)
{
    t.join();
}

assert(x == 0);

Meta