Skip to content

Latest commit

 

History

History
112 lines (81 loc) · 3.62 KB

README.md

File metadata and controls

112 lines (81 loc) · 3.62 KB

Thread

Swift Zewo Platform License Slack Travis Codebeat

Overview

Thread is a concise and type-safe wrapper around the POSIX pthread API.

Installation

import PackageDescription

let package = Package(
    dependencies: [
        .Package(url: "https://github.com/Zewo/Thread.git", majorVersion: 0, minor: 7),
    ]
)

Compiles with the 05-09 snapshot. Compatibility with other versions of Swift is not guaranteed.

Usage

Most methods have doc comments which can be another helpful source of documentation. Unit tests can also be used as examples.

Creating a thread

let thread = try Thread {
    print("I'm on a different thread!")
}

The closure passed to the Thread initializer is immediately executed on a new thread.

Waiting for the result

let thread = try Thread<Int> {
     return [1, 2, 3, 4, 5].reduce(0, combine: +)
}
let sum = try thread.wait() // 15

The wait method suspends the execution of the current thread until the called thread exits. It then returns the result of the routine given to the thread.

WARNING: Manual calls to pthread_exit with a non-nil parameter are almost guaranteed to crash your application.

Using a lock

A lock is a simple concurrency primitive which can be used to achieve thread-safety.

The lock can be locked with acquire and unlocked with release. The withLock method acquires the lock for the duration of the passed in closure.

let lock = try Lock()
var shared = 0
for _ in 1...1000 {
  try Thread {
      try lock.withLock {
          shared += 1
      }
  }
}

Using locks with conditions

A condition is a concurrency primitive which can be used to notify other threads when an action occurs.

let delay = try Condition()
let lock = try Lock()
try Thread {
    sleep(1)
    delay.resolve()
}
try lock.withLock {
    lock.wait(for: delay)
}

Support

If you need any help you can join our Slack and go to the #help channel. Or you can create a Github issue in our main repository. When stating your issue be sure to add enough details, specify what module is causing the problem and reproduction steps.

Community

Slack

The entire Zewo code base is licensed under MIT. By contributing to Zewo you are contributing to an open and engaged community of brilliant Swift programmers. Join us on Slack to get to know us!

License

This project is released under the MIT license. See LICENSE for details.