-
Notifications
You must be signed in to change notification settings - Fork 685
Fix NioAsyncWriter test on concurrency thread pool with single thread #3135
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
glbrntt
merged 15 commits into
apple:main
from
orobio:fix-NIOAsyncWriter-test-on-concurrency-thread-pool-with-single-thread
May 12, 2025
Merged
Changes from 4 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
ee05a53
Make sure NIOAsyncWriter test doesn't hang indefinitely
orobio 04e2e44
Add NIOThreadPoolTaskExecutor to NIOTestUtils
orobio b83d90d
Use NIOThreadPoolTaskExecutor for NIOAsyncWriter test that hangs on A…
orobio 7af7145
Rename test to fit with the section it's in
orobio c778a2f
Fix year in copyright notice
orobio e993300
Fix year in copyright notice
orobio 4634b06
Make NIOThreadPoolTaskExecutor member functions internal and @usableF…
orobio b0ba0b8
Merge branch 'main' into fix-NIOAsyncWriter-test-on-concurrency-threa…
glbrntt d885e38
Merge branch 'main' into fix-NIOAsyncWriter-test-on-concurrency-threa…
glbrntt 8afbc3f
Use ManualTaskExecutor instead of NIOThreadPoolTaskExecutor
orobio 5766412
Change ManualTaskExecutor related functionality from public to package
orobio 42a1c1c
Merge branch 'main' into fix-NIOAsyncWriter-test-on-concurrency-threa…
Lukasa 21487cb
Fix newline at end of file
orobio 9c579b5
Include availability declaration with visionOS in #if compiler(>=6)
orobio 3a5833a
Merge branch 'main' into fix-NIOAsyncWriter-test-on-concurrency-threa…
glbrntt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the SwiftNIO open source project | ||
// | ||
// Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
#if compiler(>=6) | ||
|
||
import NIOPosix | ||
|
||
/// Run a `NIOThreadPool` based `TaskExecutor` while executing the given `body`. | ||
orobio marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/// | ||
/// This function provides a `TaskExecutor`, **not** a `SerialExecutor`. The executor can be | ||
/// used for setting the executor preference of a task. | ||
/// | ||
/// Example usage: | ||
/// ```swift | ||
/// await withNIOThreadPoolTaskExecutor(numberOfThreads: 2) { taskExecutor in | ||
/// await withDiscardingTaskGroup { group in | ||
/// group.addTask(executorPreference: taskExecutor) { ... } | ||
/// } | ||
/// } | ||
/// ``` | ||
/// | ||
/// - warning: Do not escape the task executor from the closure for later use and make sure that | ||
/// all tasks running on the executor are completely finished before `body` returns. | ||
/// For unstructured tasks, this means awaiting their results. If any task is still | ||
/// running on the executor when `body` returns, this results in a fatalError. | ||
/// It is highly recommended to use structured concurrency with this task executor. | ||
/// | ||
/// - Parameters: | ||
/// - numberOfThreads: The number of threads in the pool. | ||
/// - body: The closure that will accept the task executor. | ||
/// | ||
/// - Throws: When `body` throws. | ||
/// | ||
/// - Returns: The value returned by `body`. | ||
@inlinable | ||
public func withNIOThreadPoolTaskExecutor<T, Failure>( | ||
orobio marked this conversation as resolved.
Show resolved
Hide resolved
|
||
numberOfThreads: Int, | ||
body: (NIOThreadPoolTaskExecutor) async throws(Failure) -> T | ||
) async throws(Failure) -> T { | ||
let taskExecutor = NIOThreadPoolTaskExecutor(numberOfThreads: numberOfThreads) | ||
taskExecutor.start() | ||
|
||
let result: Result<T, Failure> | ||
do { | ||
result = .success(try await body(taskExecutor)) | ||
} catch { | ||
result = .failure(error) | ||
} | ||
|
||
await taskExecutor.shutdownGracefully() | ||
|
||
return try result.get() | ||
} | ||
|
||
/// A task executor based on NIOThreadPool. | ||
/// | ||
/// Provides a `TaskExecutor`, **not** a `SerialExecutor`. The executor can be | ||
/// used for setting the executor preference of a task. | ||
/// | ||
public final class NIOThreadPoolTaskExecutor: TaskExecutor { | ||
let nioThreadPool: NIOThreadPool | ||
|
||
/// Initialize a `NIOThreadPoolTaskExecutor`, using a thread pool with `numberOfThreads` threads. | ||
/// | ||
/// - Parameters: | ||
/// - numberOfThreads: The number of threads to use for the thread pool. | ||
public init(numberOfThreads: Int) { | ||
self.nioThreadPool = NIOThreadPool(numberOfThreads: numberOfThreads) | ||
} | ||
|
||
/// Start the `NIOThreadPoolTaskExecutor`. | ||
public func start() { | ||
nioThreadPool.start() | ||
} | ||
|
||
/// Gracefully shutdown this `NIOThreadPoolTaskExecutor`. | ||
/// | ||
/// Make sure that all tasks running on the executor are finished before shutting down. | ||
/// | ||
/// - warning: If any task is still running on the executor, this results in a fatalError. | ||
public func shutdownGracefully() async { | ||
do { | ||
try await nioThreadPool.shutdownGracefully() | ||
} catch { | ||
fatalError("Failed to shutdown NIOThreadPool") | ||
} | ||
} | ||
orobio marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/// Enqueue a job. | ||
/// | ||
/// Called by the concurrency runtime. | ||
/// | ||
/// - Parameter job: The job to enqueue. | ||
public func enqueue(_ job: consuming ExecutorJob) { | ||
let unownedJob = UnownedJob(job) | ||
self.nioThreadPool.submit { shouldRun in | ||
guard case shouldRun = NIOThreadPool.WorkItemState.active else { | ||
fatalError("Shutdown before all tasks finished") | ||
} | ||
unownedJob.runSynchronously(on: self.asUnownedTaskExecutor()) | ||
} | ||
} | ||
} | ||
|
||
#endif // compiler(>=6) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
81 changes: 81 additions & 0 deletions
81
Tests/NIOTestUtilsTests/NIOThreadPoolTaskExecutorTest.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the SwiftNIO open source project | ||
// | ||
// Copyright (c) 2019-2025 Apple Inc. and the SwiftNIO project authors | ||
orobio marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import NIOConcurrencyHelpers | ||
import NIOTestUtils | ||
import XCTest | ||
|
||
class NIOThreadPoolTaskExecutorTest: XCTestCase { | ||
struct TestError: Error {} | ||
|
||
func runTasksSimultaneously(numberOfTasks: Int) async { | ||
await withNIOThreadPoolTaskExecutor(numberOfThreads: numberOfTasks) { taskExecutor in | ||
await withDiscardingTaskGroup { group in | ||
var taskBlockers = [ConditionLock<Bool>]() | ||
defer { | ||
// Unblock all tasks | ||
for taskBlocker in taskBlockers { | ||
taskBlocker.lock() | ||
taskBlocker.unlock(withValue: true) | ||
} | ||
} | ||
|
||
for taskNumber in 1...numberOfTasks { | ||
let taskStarted = ConditionLock(value: false) | ||
let taskBlocker = ConditionLock(value: false) | ||
taskBlockers.append(taskBlocker) | ||
|
||
// Start task and block it | ||
group.addTask(executorPreference: taskExecutor) { | ||
taskStarted.lock() | ||
taskStarted.unlock(withValue: true) | ||
taskBlocker.lock(whenValue: true) | ||
taskBlocker.unlock() | ||
} | ||
|
||
// Verify that task was able to start | ||
if taskStarted.lock(whenValue: true, timeoutSeconds: 5) { | ||
taskStarted.unlock() | ||
} else { | ||
XCTFail("Task \(taskNumber) failed to start.") | ||
break | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
func testRunsTaskOnSingleThread() async { | ||
await runTasksSimultaneously(numberOfTasks: 1) | ||
} | ||
|
||
func testRunsMultipleTasksOnMultipleThreads() async { | ||
await runTasksSimultaneously(numberOfTasks: 3) | ||
} | ||
|
||
func testReturnsBodyResult() async { | ||
let expectedResult = "result" | ||
let result = await withNIOThreadPoolTaskExecutor(numberOfThreads: 1) { _ in return expectedResult } | ||
XCTAssertEqual(result, expectedResult) | ||
} | ||
|
||
func testRethrows() async { | ||
do { | ||
try await withNIOThreadPoolTaskExecutor(numberOfThreads: 1) { _ in throw TestError() } | ||
XCTFail("Function did not rethrow.") | ||
} catch { | ||
XCTAssertTrue(error is TestError) | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.