Add docs for concurrency helpers

This commit is contained in:
Cory Benfield committed 2017-11-30 14:36:55 +00:00
1 parent 8549f4229e
commit 5958fdff73
2 files changed
+130 -1

No files matched your search

@@ -14,33 +14,105 @@
import CNIOAtomics
/// An encapsulation of an atomic primitive object.
///
/// Atomic objects support a wide range of atomic operations:
///
/// - Compare and swap
/// - Add
/// - Subtract
/// - Exchange
/// - Load current value
/// - Store current value
///
/// Atomic primitives are useful when building constructs that need to
/// communicate or cooperate across multiple threads. In the case of
/// SwiftNIO this usually involves communicating across multiple event loops.
///
/// By necessity, all atomic values are references: after all, it makes no
/// sense to talk about managing an atomic value when each time it's modified
/// the thread that modified it gets a local copy!
public final class Atomic<T: AtomicPrimitive> {
private let value: OpaquePointer
/// Create an atomic object with `value`.
public init(value: T) {
self.value = T.atomic_create(value)
}
/// Atomically compares the value against `expected` and, if they are equal,
/// replaces the value with `desired`.
///
/// This implementation conforms to C11's `atomic_compare_exchange_strong`. This
/// means that the compare-and-swap will always succeed if `expected` is equal to
/// value. Additionally, it uses a *sequentially consistent ordering*. For more
/// details on atomic memory models, check the documentation for C11's
/// `stdatomic.h`.
///
/// - Parameter expected: The value that this object must currently hold for the
/// compare-and-swap to succeed.
/// - Parameter desired: The new value that this object will hold if the compare
/// succeeds.
/// - Returns: `True` if the exchange occurred, or `False` if `expected` did not
/// match the current value and so no exchange occurred.
public func compareAndExchange(expected: T, desired: T) -> Bool {
return T.atomic_compare_and_exchange(self.value, expected, desired)
}
/// Atomically adds `rhs` to this object.
///
/// This implementation uses a *relaxed* memory ordering. This guarantees nothing
/// more than that this operation is atomic: there is no guarantee that any other
/// event will be ordered before or after this one.
///
/// - Parameter rhs: The value to add to this object.
/// - Returns: The previous value of this object, before the addition occurred.
public func add(_ rhs: T) -> T {
return T.atomic_add(self.value, rhs)
}
/// Atomically subtracts `rhs` from this object.
///
/// This implementation uses a *relaxed* memory ordering. This guarantees nothing
/// more than that this operation is atomic: there is no guarantee that any other
/// event will be ordered before or after this one.
///
/// - Parameter rhs: The value to subtract from this object.
/// - Returns: The previous value of this object, before the subtraction occurred.
public func sub(_ rhs: T) -> T {
return T.atomic_sub(self.value, rhs)
}
/// Atomically exchanges `value` for the current value of this object.
///
/// This implementation uses a *relaxed* memory ordering. This guarantees nothing
/// more than that this operation is atomic: there is no guarantee that any other
/// event will be ordered before or after this one.
///
/// - Parameter value: The new value to set this object to.
/// - Returns: The value previously held by this object.
public func exchange(with value: T) -> T {
return T.atomic_exchange(self.value, value)
}
/// Atomically loads and returns the value of this object.
///
/// This implementation uses a *relaxed* memory ordering. This guarantees nothing
/// more than that this operation is atomic: there is no guarantee that any other
/// event will be ordered before or after this one.
///
/// - Returns: The value of this object
public func load() -> T {
return T.atomic_load(self.value)
}
/// Atomically replaces the value of this object with `value`.
///
/// This implementation uses a *relaxed* memory ordering. This guarantees nothing
/// more than that this operation is atomic: there is no guarantee that any other
/// event will be ordered before or after this one.
///
/// - Parameter value: The new value to set the object to.
public func store(_ value: T) -> Void {
T.atomic_store(self.value, value)
}
@@ -50,6 +122,11 @@ public final class Atomic<T: AtomicPrimitive> {
}
}
/// The protocol that all types that can be made atomic must conform to.
///
/// **Do not add conformance to this protocol for arbitrary types**. Only a small range
/// of types have appropriate atomic operations supported by the CPU, and those types
/// already have conformances implemented.
public protocol AtomicPrimitive {
static var atomic_create: (Self) -> OpaquePointer { get }
static var atomic_destroy: (OpaquePointer) -> Void { get }
+53 -1
View File
@@ -18,9 +18,15 @@ import Darwin
import Glibc
#endif
/// A threading lock based on `libpthread` instead of `libdispatch`.
///
/// This object provides a lock on top of a single `pthread_mutex_t`. This kind
/// of lock is safe to use with `libpthread`-based threading models, such as the
/// one used by NIO.
public final class Lock {
fileprivate let mutex: UnsafeMutablePointer<pthread_mutex_t> = UnsafeMutablePointer.allocate(capacity: 1)
/// Create a new lock.
public init() {
let err = pthread_mutex_init(self.mutex, nil)
precondition(err == 0)
@@ -30,11 +36,19 @@ public final class Lock {
mutex.deallocate(capacity: 1)
}
/// Acquire the lock.
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `unlock`, to simplify lock handling.
public func lock() {
let err = pthread_mutex_lock(self.mutex)
precondition(err == 0)
}
/// Release the lock.
///
/// Whenver possible, consider using `withLock` instead of this method and
/// `lock`, to simplify lock handling.
public func unlock() {
let err = pthread_mutex_unlock(self.mutex)
precondition(err == 0)
@@ -42,6 +56,14 @@ public final class Lock {
}
extension Lock {
/// Acquire the lock for the duration of the given block.
///
/// This convenience method should be preferred to `lock` and `unlock` in
/// most situations, as it ensures that the lock will be released regardless
/// of how `fn` exits.
///
/// - Parameter fn: The block to execute while holding the lock.
/// - Returns: The value returned by the block.
public func withLock<T>(_ fn: () throws -> T) rethrows -> T {
self.lock()
defer {
@@ -56,11 +78,18 @@ extension Lock {
}
}
/// A `Lock` with a built-in state variable.
///
/// This class provides a convenience addition to `Lock`: it provides the ability to wait
/// until the state variable is set to a specific value to acquire the lock.
public final class ConditionLock<T: Equatable> {
private var _value: T
private let mutex: Lock
private let cond: UnsafeMutablePointer<pthread_cond_t> = UnsafeMutablePointer.allocate(capacity: 1)
/// Create the lock, and initialize the state variable to `value`.
///
/// - Parameter value: The initial value to give the state variable.
public init(value: T) {
self._value = value
self.mutex = Lock()
@@ -72,14 +101,21 @@ public final class ConditionLock<T: Equatable> {
self.cond.deallocate(capacity: 1)
}
/// Acquire the lock, regardless of the value of the state variable.
public func lock() {
self.mutex.lock()
}
/// Release the lock, regardless of the value of the state variable.
public func unlock() {
self.mutex.unlock()
}
/// The value of the state variable.
///
/// Obtaining the value of the state variable requires acquiring the lock.
/// This means that it is not safe to access this property while holding the
/// lock: it is only safe to use it when not holding it.
public var value: T {
self.lock()
defer {
@@ -88,6 +124,10 @@ public final class ConditionLock<T: Equatable> {
return self._value
}
/// Acquire the lock when the state variable is equal to `wantedValue`.
///
/// - Parameter wantedValue: The value to wait for the state variable
/// to have before acquiring the lock.
public func lock(whenValue wantedValue: T) {
self.lock()
while true {
@@ -99,7 +139,15 @@ public final class ConditionLock<T: Equatable> {
}
}
public func lock(whenValue wantedValue: T, timeoutSeconds: Double) -> Bool{
/// Acquire the lock when the state variable is equal to `wantedValue`,
/// waiting no more than `timeoutSeconds` seconds.
///
/// - Parameter wantedValue: The value to wait for the state variable
/// to have before acquiring the lock.
/// - Parameter timeoutSeconds: The number of seconds to wait to acquire
/// the lock before giving up.
/// - Returns: `true` if the lock was acquired, `false` if the wait timed out.
public func lock(whenValue wantedValue: T, timeoutSeconds: Double) -> Bool {
precondition(timeoutSeconds >= 0)
let nsecPerSec: Int64 = 1000000000
@@ -131,6 +179,10 @@ public final class ConditionLock<T: Equatable> {
}
}
/// Release the lock, setting the state variable to `newValue`.
///
/// - Parameter newValue: The value to give to the state variable when we
/// release the lock.
public func unlock(withValue newValue: T) {
self._value = newValue
self.unlock()