[TaskLocals] set task local value in synchronous function

This commit is contained in:
Konrad `ktoso` Malawski
2021-04-22 16:37:54 +09:00
parent f0781b1f8b
commit df5ff42d79
2 changed files with 90 additions and 1 deletions

View File

@@ -28,7 +28,7 @@ public final class TaskLocal<Value: Sendable>: CustomStringConvertible {
public struct Access: CustomStringConvertible {
let key: Builtin.RawPointer
let key: Builtin.RawPointer
let defaultValue: Value
init(key: TaskLocal<Value>, defaultValue: Value) {
@@ -103,6 +103,29 @@ extension TaskLocal {
}
}
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension UnsafeCurrentTask {
/// Allows for executing a synchronous `body` while binding a task-local value
/// in the current task.
///
/// This function MUST NOT be invoked by any other task than the current task
/// represented by this object.
@discardableResult
public func withTaskLocal<Value: Sendable, R>(
_ access: TaskLocal<Value>.Access, boundTo valueDuringBody: Value,
do body: () throws -> R,
file: String = #file, line: UInt = #line) rethrows -> R {
// check if we're not trying to bind a value from an illegal context; this may crash
_checkIllegalTaskLocalBindingWithinWithTaskGroup(file: file, line: line)
_taskLocalValuePush(self._task, key: access.key, value: valueDuringBody)
defer { _taskLocalValuePop(_task) }
return try body()
}
}
// ==== ------------------------------------------------------------------------
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)