mirror of
https://github.com/apple/swift.git
synced 2025-12-21 12:14:44 +01:00
* [WIP] Initial draft at v2 Clock/Instant/Duration * Ensure the literal types for _DoubleWide are able to be at least 64 bits on 32 bit platforms * static cast timespec members to long * Remove runtime exports from clock functions * Export clock functions in implementations as they are in headers * Clean up internal properties by adding leading underscores, refine availability to a TBD marker macro, and break at 80 lines to match style * Shift operators to concrete Instant types to avoid complexity in solver resolution * Adjust diagnostic note and error expectation of ambiguities to reflect new potential solver (perhaps incorrect) solutions * Update stdlib/public/Concurrency/TaskSleep.swift Co-authored-by: Karoy Lorentey <klorentey@apple.com> * [stdlib][NFC] Remove trailing whitespace * [stdlib] Remove _DoubleWidth from stdlib's ABI * [stdlib] Strip downd _DoubleWidth to _[U]Int128 * Additional adjustments to diagnostic notes and errors expectation of ambiguities to reflect new potential solver (perhaps incorrect) solutions * Disable type checker performance validation for operator overload inferences (rdar://33958047) * Decorate Duration, DurationProtocol, Instant and clocks with @available(SwiftStdlib 9999, *) * Restore diagnostic ambiguity test assertion (due to availability) * Add a rough attempt at implementing time accessors on win32 * Remove unused clock id, rename SPI for swift clock ids and correct a few more missing availabilities * remove obsolete case of realtime clock for dispatch after callout * Use the default implementation of ~ for Int128 and UInt128 * Ensure diagnostic ambiguitiy applies evenly to all platforms and their resolved types * Restore the simd vector build modifications (merge damage) * Update to latest naming results for Instant.Duration * Updates to latest proposal initializers and accessors and adjust encoding/decoding to string based serialization * Update availability for Clock/Instant/Duration methods and types to be 5.7 * Correct *Clock.now to report via the correct runtime API * Ensure the hashing of Duration is based upon the attoseconds hashing * Avoid string based encoding and resort back to high and low bit encoding/decoding but as unkeyed * Adjust naming of component initializer to use suffixes on parameters * Duration decoding should use a mutable container for decoding * fix up components initializer and decode access * Add platform base initializers for timespec and tiemval to and from Duration * Add some first draft documentation for standard library types Duration, DurationProtocol and InstantProtocol * Another round of documentation prose and some drive-by availability fixes * InstantProtocol availability should be 5.7 * Correct linux timeval creation to be Int and not Int32 Co-authored-by: Karoy Lorentey <klorentey@apple.com>
427 lines
14 KiB
Swift
427 lines
14 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the Swift.org open source project
|
|
//
|
|
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
|
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
//
|
|
// See https://swift.org/LICENSE.txt for license information
|
|
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
import Swift
|
|
@_implementationOnly import _SwiftConcurrencyShims
|
|
|
|
@available(SwiftStdlib 5.1, *)
|
|
extension Task where Success == Never, Failure == Never {
|
|
@available(*, deprecated, renamed: "Task.sleep(nanoseconds:)")
|
|
/// Suspends the current task for at least the given duration
|
|
/// in nanoseconds.
|
|
///
|
|
/// This function doesn't block the underlying thread.
|
|
public static func sleep(_ duration: UInt64) async {
|
|
return await Builtin.withUnsafeContinuation {
|
|
(continuation: Builtin.RawUnsafeContinuation) -> Void in
|
|
let job = _taskCreateNullaryContinuationJob(
|
|
priority: Int(Task.currentPriority.rawValue),
|
|
continuation: continuation)
|
|
_enqueueJobGlobalWithDelay(duration, job)
|
|
}
|
|
}
|
|
|
|
/// The type of continuation used in the implementation of
|
|
/// sleep(nanoseconds:).
|
|
private typealias SleepContinuation = UnsafeContinuation<(), Error>
|
|
|
|
/// Describes the state of a sleep() operation.
|
|
private enum SleepState {
|
|
/// The sleep continuation has not yet begun.
|
|
case notStarted
|
|
|
|
// The sleep continuation has been created and is available here.
|
|
case activeContinuation(SleepContinuation)
|
|
|
|
/// The sleep has finished.
|
|
case finished
|
|
|
|
/// The sleep was canceled.
|
|
case cancelled
|
|
|
|
/// The sleep was canceled before it even got started.
|
|
case cancelledBeforeStarted
|
|
|
|
/// Decode sleep state from the word of storage.
|
|
init(word: Builtin.Word) {
|
|
switch UInt(word) & 0x03 {
|
|
case 0:
|
|
let continuationBits = UInt(word) & ~0x03
|
|
if continuationBits == 0 {
|
|
self = .notStarted
|
|
} else {
|
|
let continuation = unsafeBitCast(
|
|
continuationBits, to: SleepContinuation.self)
|
|
self = .activeContinuation(continuation)
|
|
}
|
|
|
|
case 1:
|
|
self = .finished
|
|
|
|
case 2:
|
|
self = .cancelled
|
|
|
|
case 3:
|
|
self = .cancelledBeforeStarted
|
|
|
|
default:
|
|
fatalError("Bitmask failure")
|
|
}
|
|
}
|
|
|
|
/// Decode sleep state by loading from the given pointer
|
|
init(loading wordPtr: UnsafeMutablePointer<Builtin.Word>) {
|
|
self.init(word: Builtin.atomicload_seqcst_Word(wordPtr._rawValue))
|
|
}
|
|
|
|
/// Encode sleep state into a word of storage.
|
|
var word: UInt {
|
|
switch self {
|
|
case .notStarted:
|
|
return 0
|
|
|
|
case .activeContinuation(let continuation):
|
|
let continuationBits = unsafeBitCast(continuation, to: UInt.self)
|
|
return continuationBits
|
|
|
|
case .finished:
|
|
return 1
|
|
|
|
case .cancelled:
|
|
return 2
|
|
|
|
case .cancelledBeforeStarted:
|
|
return 3
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Called when the sleep(nanoseconds:) operation woke up without being
|
|
/// canceled.
|
|
private static func onSleepWake(
|
|
_ wordPtr: UnsafeMutablePointer<Builtin.Word>
|
|
) {
|
|
while true {
|
|
let state = SleepState(loading: wordPtr)
|
|
switch state {
|
|
case .notStarted:
|
|
fatalError("Cannot wake before we even started")
|
|
|
|
case .activeContinuation(let continuation):
|
|
// We have an active continuation, so try to transition to the
|
|
// "finished" state.
|
|
let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
|
|
wordPtr._rawValue,
|
|
state.word._builtinWordValue,
|
|
SleepState.finished.word._builtinWordValue)
|
|
if Bool(_builtinBooleanLiteral: won) {
|
|
// The sleep finished, so invoke the continuation: we're done.
|
|
continuation.resume()
|
|
return
|
|
}
|
|
|
|
// Try again!
|
|
continue
|
|
|
|
case .finished:
|
|
fatalError("Already finished normally, can't do that again")
|
|
|
|
case .cancelled:
|
|
// The task was cancelled, which means the continuation was
|
|
// called by the cancellation handler. We need to deallocate the flag
|
|
// word, because it was left over for this task to complete.
|
|
wordPtr.deallocate()
|
|
return
|
|
|
|
case .cancelledBeforeStarted:
|
|
// Nothing to do;
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Called when the sleep(nanoseconds:) operation has been canceled before
|
|
/// the sleep completed.
|
|
private static func onSleepCancel(
|
|
_ wordPtr: UnsafeMutablePointer<Builtin.Word>
|
|
) {
|
|
while true {
|
|
let state = SleepState(loading: wordPtr)
|
|
switch state {
|
|
case .notStarted:
|
|
// We haven't started yet, so try to transition to the cancelled-before
|
|
// started state.
|
|
let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
|
|
wordPtr._rawValue,
|
|
state.word._builtinWordValue,
|
|
SleepState.cancelledBeforeStarted.word._builtinWordValue)
|
|
if Bool(_builtinBooleanLiteral: won) {
|
|
return
|
|
}
|
|
|
|
// Try again!
|
|
continue
|
|
|
|
case .activeContinuation(let continuation):
|
|
// We have an active continuation, so try to transition to the
|
|
// "cancelled" state.
|
|
let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
|
|
wordPtr._rawValue,
|
|
state.word._builtinWordValue,
|
|
SleepState.cancelled.word._builtinWordValue)
|
|
if Bool(_builtinBooleanLiteral: won) {
|
|
// We recorded the task cancellation before the sleep finished, so
|
|
// invoke the continuation with the cancellation error.
|
|
continuation.resume(throwing: _Concurrency.CancellationError())
|
|
return
|
|
}
|
|
|
|
// Try again!
|
|
continue
|
|
|
|
case .finished, .cancelled, .cancelledBeforeStarted:
|
|
// The operation already finished, so there is nothing more to do.
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Suspends the current task for at least the given duration
|
|
/// in nanoseconds.
|
|
///
|
|
/// If the task is canceled before the time ends,
|
|
/// this function throws `CancellationError`.
|
|
///
|
|
/// This function doesn't block the underlying thread.
|
|
public static func sleep(nanoseconds duration: UInt64) async throws {
|
|
// Allocate storage for the storage word.
|
|
let wordPtr = UnsafeMutablePointer<Builtin.Word>.allocate(capacity: 1)
|
|
|
|
// Initialize the flag word to "not started", which means the continuation
|
|
// has neither been created nor completed.
|
|
Builtin.atomicstore_seqcst_Word(
|
|
wordPtr._rawValue, SleepState.notStarted.word._builtinWordValue)
|
|
|
|
do {
|
|
// Install a cancellation handler to resume the continuation by
|
|
// throwing CancellationError.
|
|
try await withTaskCancellationHandler {
|
|
let _: () = try await withUnsafeThrowingContinuation { continuation in
|
|
while true {
|
|
let state = SleepState(loading: wordPtr)
|
|
switch state {
|
|
case .notStarted:
|
|
// The word that describes the active continuation state.
|
|
let continuationWord =
|
|
SleepState.activeContinuation(continuation).word
|
|
|
|
// Try to swap in the continuation word.
|
|
let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
|
|
wordPtr._rawValue,
|
|
state.word._builtinWordValue,
|
|
continuationWord._builtinWordValue)
|
|
if !Bool(_builtinBooleanLiteral: won) {
|
|
// Keep trying!
|
|
continue
|
|
}
|
|
|
|
// Create a task that resumes the continuation normally if it
|
|
// finishes first. Enqueue it directly with the delay, so it fires
|
|
// when we're done sleeping.
|
|
let sleepTaskFlags = taskCreateFlags(
|
|
priority: nil, isChildTask: false, copyTaskLocals: false,
|
|
inheritContext: false, enqueueJob: false,
|
|
addPendingGroupTaskUnconditionally: false)
|
|
let (sleepTask, _) = Builtin.createAsyncTask(sleepTaskFlags) {
|
|
onSleepWake(wordPtr)
|
|
}
|
|
_enqueueJobGlobalWithDelay(
|
|
duration, Builtin.convertTaskToJob(sleepTask))
|
|
return
|
|
|
|
case .activeContinuation, .finished:
|
|
fatalError("Impossible to have multiple active continuations")
|
|
|
|
case .cancelled:
|
|
fatalError("Impossible to have cancelled before we began")
|
|
|
|
case .cancelledBeforeStarted:
|
|
// Finish the continuation normally. We'll throw later, after
|
|
// we clean up.
|
|
continuation.resume()
|
|
return
|
|
}
|
|
}
|
|
}
|
|
} onCancel: {
|
|
onSleepCancel(wordPtr)
|
|
}
|
|
|
|
// Determine whether we got cancelled before we even started.
|
|
let cancelledBeforeStarted: Bool
|
|
switch SleepState(loading: wordPtr) {
|
|
case .notStarted, .activeContinuation, .cancelled:
|
|
fatalError("Invalid state for non-cancelled sleep task")
|
|
|
|
case .cancelledBeforeStarted:
|
|
cancelledBeforeStarted = true
|
|
|
|
case .finished:
|
|
cancelledBeforeStarted = false
|
|
}
|
|
|
|
// We got here without being cancelled, so deallocate the storage for
|
|
// the flag word and continuation.
|
|
wordPtr.deallocate()
|
|
|
|
// If we got cancelled before we even started, through the cancellation
|
|
// error now.
|
|
if cancelledBeforeStarted {
|
|
throw _Concurrency.CancellationError()
|
|
}
|
|
} catch {
|
|
// The task was cancelled; propagate the error. The "on wake" task is
|
|
// responsible for deallocating the flag word and continuation, if it's
|
|
// still running.
|
|
throw error
|
|
}
|
|
}
|
|
|
|
@available(SwiftStdlib 5.7, *)
|
|
internal static func _sleep(
|
|
until seconds: Int64, _ nanoseconds: Int64,
|
|
tolerance: Duration?,
|
|
clock: _ClockID
|
|
) async throws {
|
|
// Allocate storage for the storage word.
|
|
let wordPtr = UnsafeMutablePointer<Builtin.Word>.allocate(capacity: 1)
|
|
|
|
// Initialize the flag word to "not started", which means the continuation
|
|
// has neither been created nor completed.
|
|
Builtin.atomicstore_seqcst_Word(
|
|
wordPtr._rawValue, SleepState.notStarted.word._builtinWordValue)
|
|
|
|
do {
|
|
// Install a cancellation handler to resume the continuation by
|
|
// throwing CancellationError.
|
|
try await withTaskCancellationHandler {
|
|
let _: () = try await withUnsafeThrowingContinuation { continuation in
|
|
while true {
|
|
let state = SleepState(loading: wordPtr)
|
|
switch state {
|
|
case .notStarted:
|
|
// The word that describes the active continuation state.
|
|
let continuationWord =
|
|
SleepState.activeContinuation(continuation).word
|
|
|
|
// Try to swap in the continuation word.
|
|
let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
|
|
wordPtr._rawValue,
|
|
state.word._builtinWordValue,
|
|
continuationWord._builtinWordValue)
|
|
if !Bool(_builtinBooleanLiteral: won) {
|
|
// Keep trying!
|
|
continue
|
|
}
|
|
|
|
// Create a task that resumes the continuation normally if it
|
|
// finishes first. Enqueue it directly with the delay, so it fires
|
|
// when we're done sleeping.
|
|
let sleepTaskFlags = taskCreateFlags(
|
|
priority: nil, isChildTask: false, copyTaskLocals: false,
|
|
inheritContext: false, enqueueJob: false,
|
|
addPendingGroupTaskUnconditionally: false)
|
|
let (sleepTask, _) = Builtin.createAsyncTask(sleepTaskFlags) {
|
|
onSleepWake(wordPtr)
|
|
}
|
|
let toleranceSeconds: Int64
|
|
let toleranceNanoseconds: Int64
|
|
if let components = tolerance?.components {
|
|
toleranceSeconds = components.seconds
|
|
toleranceNanoseconds = components.attoseconds / 1_000_000_000
|
|
} else {
|
|
toleranceSeconds = 0
|
|
toleranceNanoseconds = -1
|
|
}
|
|
|
|
_enqueueJobGlobalWithDeadline(
|
|
seconds, nanoseconds,
|
|
toleranceSeconds, toleranceNanoseconds,
|
|
clock.rawValue, Builtin.convertTaskToJob(sleepTask))
|
|
return
|
|
|
|
case .activeContinuation, .finished:
|
|
fatalError("Impossible to have multiple active continuations")
|
|
|
|
case .cancelled:
|
|
fatalError("Impossible to have cancelled before we began")
|
|
|
|
case .cancelledBeforeStarted:
|
|
// Finish the continuation normally. We'll throw later, after
|
|
// we clean up.
|
|
continuation.resume()
|
|
return
|
|
}
|
|
}
|
|
}
|
|
} onCancel: {
|
|
onSleepCancel(wordPtr)
|
|
}
|
|
|
|
// Determine whether we got cancelled before we even started.
|
|
let cancelledBeforeStarted: Bool
|
|
switch SleepState(loading: wordPtr) {
|
|
case .notStarted, .activeContinuation, .cancelled:
|
|
fatalError("Invalid state for non-cancelled sleep task")
|
|
|
|
case .cancelledBeforeStarted:
|
|
cancelledBeforeStarted = true
|
|
|
|
case .finished:
|
|
cancelledBeforeStarted = false
|
|
}
|
|
|
|
// We got here without being cancelled, so deallocate the storage for
|
|
// the flag word and continuation.
|
|
wordPtr.deallocate()
|
|
|
|
// If we got cancelled before we even started, through the cancellation
|
|
// error now.
|
|
if cancelledBeforeStarted {
|
|
throw _Concurrency.CancellationError()
|
|
}
|
|
} catch {
|
|
// The task was cancelled; propagate the error. The "on wake" task is
|
|
// responsible for deallocating the flag word and continuation, if it's
|
|
// still running.
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/// Suspends the current task until the given deadline within a tolerance.
|
|
///
|
|
/// If the task is canceled before the time ends, this function throws
|
|
/// `CancellationError`.
|
|
///
|
|
/// This function doesn't block the underlying thread.
|
|
///
|
|
/// try await Task.sleep(until: .now + .seconds(3), clock: .continuous)
|
|
///
|
|
@available(SwiftStdlib 5.7, *)
|
|
public static func sleep<C: Clock>(
|
|
until deadine: C.Instant,
|
|
tolerance: C.Instant.Duration? = nil,
|
|
clock: C
|
|
) async throws {
|
|
try await clock.sleep(until: deadine, tolerance: tolerance)
|
|
}
|
|
}
|