Thread is a concise and type-safe wrapper around the POSIX pthread
API.
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.
Most methods have doc comments which can be another helpful source of documentation. Unit tests can also be used as examples.
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.
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.
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
}
}
}
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)
}
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.
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!
This project is released under the MIT license. See LICENSE for details.