Skip to content

Commit a9ed11c

Browse files
committed
[Concurrency] Fix race condition in _runAsyncMain.
As of the custom main/global executor changes, there is a race in `_runAsyncMain()` to construct the main executor; if this goes the wrong way, the IRGen async tests, which use this function, can fail. Fix by explicitly constructing a task and enqueing it on the main executor, instead of detaching a task and trying to hop to it. rdar://148506256
1 parent aedb869 commit a9ed11c

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

stdlib/public/Concurrency/Task.swift

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1500,21 +1500,28 @@ internal func _runAsyncMain(_ asyncFun: @Sendable @escaping () async throws -> (
15001500
@usableFromInline
15011501
@preconcurrency
15021502
internal func _runAsyncMain(_ asyncFun: @Sendable @escaping () async throws -> ()) {
1503-
Task.detached {
1503+
let taskFlags = taskCreateFlags(
1504+
priority: nil, isChildTask: false, copyTaskLocals: false,
1505+
inheritContext: false, enqueueJob: false,
1506+
addPendingGroupTaskUnconditionally: false,
1507+
isDiscardingTask: false, isSynchronousStart: false)
1508+
1509+
let (theTask, _) = Builtin.createAsyncTask(taskFlags) {
15041510
do {
1505-
#if !os(Windows)
1506-
#if compiler(>=5.5) && $BuiltinHopToActor
1507-
Builtin.hopToActor(MainActor.shared)
1508-
#else
1509-
fatalError("Swift compiler is incompatible with this SDK version")
1510-
#endif
1511-
#endif
15121511
try await asyncFun()
15131512
exit(0)
15141513
} catch {
15151514
_errorInMain(error)
15161515
}
15171516
}
1517+
1518+
let job = Builtin.convertTaskToJob(theTask)
1519+
if #available(SwiftStdlib 6.2, *) {
1520+
MainActor.executor.enqueue(ExecutorJob(context: job))
1521+
} else {
1522+
Builtin.unreachable()
1523+
}
1524+
15181525
_asyncMainDrainQueue()
15191526
}
15201527
#endif

0 commit comments

Comments
 (0)