|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the SwiftNIO open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +#if compiler(>=6) |
| 16 | + |
| 17 | +import DequeModule |
| 18 | +import Synchronization |
| 19 | + |
| 20 | +/// Provide a `ManualTaskExecutor` for the duration of the given `body`. |
| 21 | +/// |
| 22 | +/// The executor can be used for setting the executor preference of tasks and fully control |
| 23 | +/// when execution of the tasks is performed. |
| 24 | +/// |
| 25 | +/// Example usage: |
| 26 | +/// ```swift |
| 27 | +/// await withDiscardingTaskGroup { group in |
| 28 | +/// await withManualTaskExecutor { taskExecutor in |
| 29 | +/// group.addTask(executorPreference: taskExecutor) { |
| 30 | +/// print("Running") |
| 31 | +/// } |
| 32 | +/// taskExecutor.runUntilQueueIsEmpty() // Run the task synchronously |
| 33 | +/// } |
| 34 | +/// } |
| 35 | +/// ``` |
| 36 | +/// |
| 37 | +/// - warning: Do not escape the task executor from the closure for later use and make sure that |
| 38 | +/// all tasks running on the executor are completely finished before `body` returns. |
| 39 | +/// It is highly recommended to use structured concurrency with this task executor. |
| 40 | +/// |
| 41 | +/// - Parameters: |
| 42 | +/// - body: The closure that will accept the task executor. |
| 43 | +/// |
| 44 | +/// - Throws: When `body` throws. |
| 45 | +/// |
| 46 | +/// - Returns: The value returned by `body`. |
| 47 | +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) |
| 48 | +@inlinable |
| 49 | +package func withManualTaskExecutor<T, Failure>( |
| 50 | + body: (ManualTaskExecutor) async throws(Failure) -> T |
| 51 | +) async throws(Failure) -> T { |
| 52 | + let taskExecutor = ManualTaskExecutor() |
| 53 | + defer { taskExecutor.shutdown() } |
| 54 | + return try await body(taskExecutor) |
| 55 | +} |
| 56 | + |
| 57 | +/// Provide two `ManualTaskExecutor`s for the duration of the given `body`. |
| 58 | +/// |
| 59 | +/// The executors can be used for setting the executor preference of tasks and fully control |
| 60 | +/// when execution of the tasks is performed. |
| 61 | +/// |
| 62 | +/// Example usage: |
| 63 | +/// ```swift |
| 64 | +/// await withDiscardingTaskGroup { group in |
| 65 | +/// await withManualTaskExecutor { taskExecutor1, taskExecutor2 in |
| 66 | +/// group.addTask(executorPreference: taskExecutor1) { |
| 67 | +/// print("Running 1") |
| 68 | +/// } |
| 69 | +/// group.addTask(executorPreference: taskExecutor2) { |
| 70 | +/// print("Running 2") |
| 71 | +/// } |
| 72 | +/// taskExecutor2.runUntilQueueIsEmpty() // Run second task synchronously |
| 73 | +/// taskExecutor1.runUntilQueueIsEmpty() // Run first task synchronously |
| 74 | +/// } |
| 75 | +/// } |
| 76 | +/// ``` |
| 77 | +/// |
| 78 | +/// - warning: Do not escape the task executors from the closure for later use and make sure that |
| 79 | +/// all tasks running on the executors are completely finished before `body` returns. |
| 80 | +/// It is highly recommended to use structured concurrency with these task executors. |
| 81 | +/// |
| 82 | +/// - Parameters: |
| 83 | +/// - body: The closure that will accept the task executors. |
| 84 | +/// |
| 85 | +/// - Throws: When `body` throws. |
| 86 | +/// |
| 87 | +/// - Returns: The value returned by `body`. |
| 88 | +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) |
| 89 | +@inlinable |
| 90 | +package func withManualTaskExecutor<T, Failure>( |
| 91 | + body: (ManualTaskExecutor, ManualTaskExecutor) async throws(Failure) -> T |
| 92 | +) async throws(Failure) -> T { |
| 93 | + let taskExecutor1 = ManualTaskExecutor() |
| 94 | + defer { taskExecutor1.shutdown() } |
| 95 | + |
| 96 | + let taskExecutor2 = ManualTaskExecutor() |
| 97 | + defer { taskExecutor2.shutdown() } |
| 98 | + |
| 99 | + return try await body(taskExecutor1, taskExecutor2) |
| 100 | +} |
| 101 | + |
| 102 | +/// Manual task executor. |
| 103 | +/// |
| 104 | +/// A `TaskExecutor` that does not use any threadpool or similar mechanism to run the jobs. |
| 105 | +/// Jobs are manually run by calling the `runUntilQueueIsEmpty` method. |
| 106 | +/// |
| 107 | +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) |
| 108 | +@usableFromInline |
| 109 | +package final class ManualTaskExecutor: TaskExecutor { |
| 110 | + struct Storage { |
| 111 | + var isShutdown = false |
| 112 | + var jobs = Deque<UnownedJob>() |
| 113 | + } |
| 114 | + |
| 115 | + private let storage = Mutex<Storage>(.init()) |
| 116 | + |
| 117 | + @usableFromInline |
| 118 | + init() {} |
| 119 | + |
| 120 | + /// Run jobs until queue is empty. |
| 121 | + /// |
| 122 | + /// Synchronously runs all enqueued jobs, including any jobs that are enqueued while running. |
| 123 | + /// When this function returns, it means that each task running on this executor is either: |
| 124 | + /// - suspended |
| 125 | + /// - moved (temporarily) to a different executor |
| 126 | + /// - finished |
| 127 | + /// |
| 128 | + /// If not all tasks are finished, this function must be called again. |
| 129 | + package func runUntilQueueIsEmpty() { |
| 130 | + while let job = self.storage.withLock({ $0.jobs.popFirst() }) { |
| 131 | + job.runSynchronously(on: self.asUnownedTaskExecutor()) |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + /// Enqueue a job. |
| 136 | + /// |
| 137 | + /// Called by the concurrency runtime. |
| 138 | + /// |
| 139 | + /// - Parameter job: The job to enqueue. |
| 140 | + @usableFromInline |
| 141 | + package func enqueue(_ job: UnownedJob) { |
| 142 | + self.storage.withLock { storage in |
| 143 | + if storage.isShutdown { |
| 144 | + fatalError("A job is enqueued after manual executor shutdown") |
| 145 | + } |
| 146 | + storage.jobs.append(job) |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + /// Shutdown. |
| 151 | + /// |
| 152 | + /// Since the manual task executor is not running anything in the background, this is purely to catch |
| 153 | + /// any issues due to incorrect usage of the executor. The shutdown verifies that the queue is empty |
| 154 | + /// and makes sure that no new jobs can be enqueued. |
| 155 | + @usableFromInline |
| 156 | + func shutdown() { |
| 157 | + self.storage.withLock { storage in |
| 158 | + if !storage.jobs.isEmpty { |
| 159 | + fatalError("Shutdown of manual executor with jobs in queue") |
| 160 | + } |
| 161 | + storage.isShutdown = true |
| 162 | + } |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +#endif // compiler(>=6) |
0 commit comments