bm842/Threads

Swift wrapper over POSIX Threads


License
MIT

Documentation

Threads

Build Status License MIT Carthage compatible

Swift wrapper over POSIX Threads

Mutex

Basic usage:

var mutex = Mutex()

mutex.lock()
//
// ... mutually exclusive section
//
mutex.unlock()

Syntactic sugar:

var mutex = Mutex()

mutex.protect
{
    //
    // ... mutually exclusive section
    //
}

Try lock:

var mutex = Mutex()

if case Result.Success = mutex.tryLock()
{
    //
    // ... mutually exclusive section
    //
   mutex.unlock()
}
else
{
    // mutex not acquired, probably Result.ResourceBusy
}        

CondVar

Basic usage

Declare the CondVar along with a Mutex:

let mutex = Mutex()
let condvar = CondVar()

In thread consumer:

mutex.lock()
condvar.wait(mutex)
// extract the resource
// ...
mutex.unlock()

In thread producer:

mutex.lock()
// insert a resource
// ...
condvar.signal()
mutex.unlock()

Other usages

Wait with a timeout:

mutex.lock()
let result = condvar.wait(mutex, until: Timespec(relative: 1000 * MilliSeconds))

if case Result.Success = result
{
    // extract the resource
    // ...
}
else // Result.Timeout
{
    // ...
}
mutex.unlock()

Signal to all threads waiting instead of only one:

// condvar.signal()
condvar.broadcast() // signal all thread waiting

Syntactic sugar to wait for a condition to happen:

func take() -> ElementType
{
    var element: ElementType!
    mutex.protect
    {
        // wait for a new element in list
        condVar.wait(mutex, until: list.isEmpty == false)
        element = list.removeFirst()
    }
    return element
}

Threads

New thread:

let thread = Thread
{
    // thread code
    // ...
}

Terminates the current running thread:

Thread.exit()

Terminates the thread from another thread:

let thread = Thread { /* ... */ }

thread.cancel()
thread.join() // optionnally waits for thread to be actually terminated

Delay execution:

Thread.sleep(200 * MilliSeconds)

Get current thread instance:

let current = Thread.current