|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2020 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | +import Swift |
| 13 | +@_implementationOnly import _SwiftConcurrencyShims |
| 14 | + |
| 15 | +@available(SwiftStdlib 5.5, *) |
| 16 | +extension Task where Success == Never, Failure == Never { |
| 17 | + /// Suspends the current task for _at least_ the given duration |
| 18 | + /// in nanoseconds. |
| 19 | + /// |
| 20 | + /// This function does _not_ block the underlying thread. |
| 21 | + public static func sleep(_ duration: UInt64) async { |
| 22 | + let currentTask = Builtin.getCurrentAsyncTask() |
| 23 | + let priority = getJobFlags(currentTask).priority ?? Task.currentPriority._downgradeUserInteractive |
| 24 | + |
| 25 | + return await Builtin.withUnsafeContinuation { (continuation: Builtin.RawUnsafeContinuation) -> Void in |
| 26 | + let job = _taskCreateNullaryContinuationJob(priority: Int(priority.rawValue), continuation: continuation) |
| 27 | + _enqueueJobGlobalWithDelay(duration, job) |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + /// The type of continuation used in the implementation of |
| 32 | + /// sleep(nanoseconds:). |
| 33 | + private typealias SleepContinuation = UnsafeContinuation<(), Error> |
| 34 | + |
| 35 | + /// Called when the sleep(nanoseconds:) operation woke up without being |
| 36 | + /// cancelled. |
| 37 | + private static func onSleepWake( |
| 38 | + _ wordPtr: UnsafeMutablePointer<Builtin.Word>, |
| 39 | + _ continuation: UnsafeContinuation<(), Error> |
| 40 | + ) { |
| 41 | + // Indicate that we've finished by putting a "1" into the flag word. |
| 42 | + let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word( |
| 43 | + wordPtr._rawValue, |
| 44 | + UInt(0)._builtinWordValue, |
| 45 | + UInt(1)._builtinWordValue) |
| 46 | + |
| 47 | + if Bool(_builtinBooleanLiteral: won) { |
| 48 | + // The sleep finished, invoke the continuation. |
| 49 | + continuation.resume() |
| 50 | + } else { |
| 51 | + // The task was cancelled first, which means the continuation was |
| 52 | + // called by the cancellation handler. We need to deallocate up the flag |
| 53 | + // word, because it was left over for this task to complete. |
| 54 | + wordPtr.deallocate() |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + /// Called when the sleep(nanoseconds:) operation has been cancelled before |
| 59 | + /// the sleep completed. |
| 60 | + private static func onSleepCancel( |
| 61 | + _ wordPtr: UnsafeMutablePointer<Builtin.Word>, |
| 62 | + _ continuation: UnsafeContinuation<(), Error> |
| 63 | + ) { |
| 64 | + // Indicate that we've finished by putting a "2" into the flag word. |
| 65 | + let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word( |
| 66 | + wordPtr._rawValue, |
| 67 | + UInt(0)._builtinWordValue, |
| 68 | + UInt(2)._builtinWordValue) |
| 69 | + |
| 70 | + if Bool(_builtinBooleanLiteral: won) { |
| 71 | + // We recorded the task cancellation before the sleep finished, so |
| 72 | + // invoke the continuation with a the cancellation error. |
| 73 | + continuation.resume(throwing: _Concurrency.CancellationError()) |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + /// Suspends the current task for _at least_ the given duration |
| 78 | + /// in nanoseconds, unless the task is cancelled. If the task is cancelled, |
| 79 | + /// throws \c CancellationError. |
| 80 | + /// |
| 81 | + /// This function does _not_ block the underlying thread. |
| 82 | + public static func sleep(nanoseconds duration: UInt64) async throws { |
| 83 | + // If the task was already cancelled, go ahead and throw now. |
| 84 | + try checkCancellation() |
| 85 | + |
| 86 | + // Allocate storage for the flag word and continuation. |
| 87 | + let wordPtr = UnsafeMutablePointer<Builtin.Word>.allocate(capacity: 2) |
| 88 | + |
| 89 | + // Initialize the flag word to 0, which means the continuation has not |
| 90 | + // executed. |
| 91 | + Builtin.atomicstore_seqcst_Word( |
| 92 | + wordPtr._rawValue, UInt(0)._builtinWordValue) |
| 93 | + |
| 94 | + // A pointer to the storage continuation. Also initialize it to zero, to |
| 95 | + // indicate that there is no continuation. |
| 96 | + let continuationPtr = wordPtr + 1 |
| 97 | + Builtin.atomicstore_seqcst_Word( |
| 98 | + continuationPtr._rawValue, UInt(0)._builtinWordValue) |
| 99 | + |
| 100 | + do { |
| 101 | + // Install a cancellation handler to resume the continuation by |
| 102 | + // throwing CancellationError. |
| 103 | + try await withTaskCancellationHandler { |
| 104 | + let _: () = try await withUnsafeThrowingContinuation { continuation in |
| 105 | + // Stash the continuation so the cancellation handler can see it. |
| 106 | + Builtin.atomicstore_seqcst_Word( |
| 107 | + continuationPtr._rawValue, |
| 108 | + unsafeBitCast(continuation, to: Builtin.Word.self)) |
| 109 | + |
| 110 | + // Create a task that resumes the continuation normally if it |
| 111 | + // finishes first. Enqueue it directly with the delay, so it fires |
| 112 | + // when we're done sleeping. |
| 113 | + let sleepTaskFlags = taskCreateFlags( |
| 114 | + priority: nil, isChildTask: false, copyTaskLocals: false, |
| 115 | + inheritContext: false, enqueueJob: false, |
| 116 | + addPendingGroupTaskUnconditionally: false) |
| 117 | + let (sleepTask, _) = Builtin.createAsyncTask(sleepTaskFlags) { |
| 118 | + onSleepWake(wordPtr, continuation) |
| 119 | + } |
| 120 | + _enqueueJobGlobalWithDelay( |
| 121 | + duration, Builtin.convertTaskToJob(sleepTask)) |
| 122 | + } |
| 123 | + } onCancel: { |
| 124 | + let continuationWord = continuationPtr.pointee |
| 125 | + if UInt(continuationWord) != 0 { |
| 126 | + // Try to cancel, which will resume the continuation by throwing a |
| 127 | + // CancellationError if the continuation hasn't already been resumed. |
| 128 | + continuationPtr.withMemoryRebound( |
| 129 | + to: SleepContinuation.self, capacity: 1) { |
| 130 | + onSleepCancel(wordPtr, $0.pointee) |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + // We got here without being cancelled, so deallocate the storage for |
| 136 | + // the flag word and continuation. |
| 137 | + wordPtr.deallocate() |
| 138 | + } catch { |
| 139 | + // The task was cancelled; propagate the error. The "on wake" task is |
| 140 | + // responsible for deallocating the flag word. |
| 141 | + throw error |
| 142 | + } |
| 143 | + } |
| 144 | +} |
0 commit comments