Skip to content

Commit 2ee7a32

Browse files
authored
Merge pull request #36239 from etcwilde/ewilde/run-async-main-on-main-thread
[Concurrency] Run async main code on main thread
2 parents 7104cb1 + 12c3eb2 commit 2ee7a32

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

stdlib/public/Concurrency/Task.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,7 @@ public func runAsyncAndBlock(_ asyncFun: @escaping () async -> ())
579579
public func _asyncMainDrainQueue() -> Never
580580

581581
public func _runAsyncMain(_ asyncFun: @escaping () async throws -> ()) {
582+
#if os(Windows)
582583
Task.runDetached {
583584
do {
584585
try await asyncFun()
@@ -587,6 +588,21 @@ public func _runAsyncMain(_ asyncFun: @escaping () async throws -> ()) {
587588
_errorInMain(error)
588589
}
589590
}
591+
#else
592+
@MainActor @concurrent
593+
func _doMain(_ asyncFun: @escaping () async throws -> ()) async {
594+
do {
595+
try await asyncFun()
596+
} catch {
597+
_errorInMain(error)
598+
}
599+
}
600+
601+
Task.runDetached {
602+
await _doMain(asyncFun)
603+
exit(0)
604+
}
605+
#endif
590606
_asyncMainDrainQueue()
591607
}
592608

test/Concurrency/Runtime/mainactor.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ actor A {
6666

6767
// CHECK: starting
6868
// CHECK-NOT: ERROR
69+
// CHECK: Hello from the main function
70+
// CHECK-NOT: ERROR
6971
// CHECK: hello from main actor!
7072
// CHECK-NOT: ERROR
7173
// CHECK: on actor instance's queue
@@ -77,6 +79,11 @@ actor A {
7779
@main struct RunIt {
7880
static func main() async {
7981
print("starting")
82+
if checkIfMainQueue(expectedAnswer: true) {
83+
print("Hello from the main function")
84+
} else {
85+
print("ERROR: not on the main queue")
86+
}
8087
let result = await someFunc()
8188
print("finished with return counter = \(result)")
8289
}

0 commit comments

Comments
 (0)