|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2025 PassiveLogic, Inc. |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of Swift.org project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
1 | 15 | import Testing
|
2 | 16 |
|
3 | 17 | @testable import DispatchAsync
|
@@ -40,3 +54,42 @@ func asyncSemaphoreWaitSignal() async throws {
|
40 | 54 |
|
41 | 55 | #expect(didEnterCriticalSection) // waiter must have run
|
42 | 56 | }
|
| 57 | + |
| 58 | +@Test func basicAsyncSemaphoreTest() async throws { |
| 59 | + nonisolated(unsafe) var sharedPoolCompletionCount = 0 |
| 60 | + sharedPoolCompletionCount = 0 // Reset to 0 for each test run |
| 61 | + let totalConcurrentPools = 10 |
| 62 | + |
| 63 | + let semaphore = AsyncSemaphore(value: 1) |
| 64 | + |
| 65 | + await withTaskGroup(of: Void.self) { group in |
| 66 | + for _ in 0 ..< totalConcurrentPools { |
| 67 | + group.addTask { |
| 68 | + // Wait for any other pools currently holding the semaphore |
| 69 | + await semaphore.wait() |
| 70 | + |
| 71 | + // Only one task should mutate counter at a time |
| 72 | + // |
| 73 | + // If there are issues with the semaphore, then |
| 74 | + // we would expect to grab incorrect values here occasionally, |
| 75 | + // which would result in an incorrect final completion count. |
| 76 | + // |
| 77 | + let existingPoolCompletionCount = sharedPoolCompletionCount |
| 78 | + |
| 79 | + // Add artificial delay to amplify race conditions |
| 80 | + // Pools started shortly after this "semaphore-locked" |
| 81 | + // pool starts will run before this line, unless |
| 82 | + // this pool contains a valid lock. |
| 83 | + try? await Task.sleep(nanoseconds: 100) |
| 84 | + |
| 85 | + sharedPoolCompletionCount = existingPoolCompletionCount + 1 |
| 86 | + |
| 87 | + // When we exit this flow, release our hold on the semaphore |
| 88 | + await semaphore.signal() |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + // After all tasks are done, counter should be 10 |
| 94 | + #expect(sharedPoolCompletionCount == totalConcurrentPools) |
| 95 | +} |
0 commit comments