Skip to content

Commit 0f67e17

Browse files
committed
Prevent termination races of Worker
Fixes #3578
1 parent 67e21b2 commit 0f67e17

File tree

2 files changed

+25
-9
lines changed

2 files changed

+25
-9
lines changed

kotlinx-coroutines-core/native/src/EventLoop.kt

+8-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,14 @@ internal actual abstract class EventLoopImplPlatform : EventLoop() {
1313
private val current = Worker.current
1414

1515
protected actual fun unpark() {
16-
current.executeAfter(0L, {})// send an empty task to unpark the waiting event loop
16+
try {
17+
current.executeAfter(0L, {}) // send an empty task to unpark the waiting event loop
18+
} catch (e: IllegalStateException) {
19+
// We deliberately ignore ISE here as they are expected
20+
// due to peculiarities of Workers API.
21+
// Unfortunately, race-free termination of workers is unachievable by its current state,
22+
// see https://github.com/Kotlin/kotlinx.coroutines/issues/3578
23+
}
1724
}
1825

1926
protected actual fun reschedule(now: Long, delayedTask: EventLoopImplBase.DelayedTask) {

kotlinx-coroutines-core/native/src/MultithreadedDispatchers.kt

+17-8
Original file line numberDiff line numberDiff line change
@@ -79,14 +79,23 @@ private class MultiWorkerDispatcher(
7979
}
8080
}
8181

82-
private fun workerRunLoop() = runBlocking {
83-
// NB: we leverage tail-call optimization in this loop, do not replace it with
84-
// .receive() without proper evaluation
85-
for (task in tasksQueue) {
86-
/**
87-
* Any unhandled exception here will pass through worker's boundary and will be properly reported.
88-
*/
89-
task.run()
82+
private fun workerRunLoop() {
83+
try {
84+
runBlocking {
85+
// NB: we leverage tail-call optimization in this loop, do not replace it with
86+
// .receive() without proper evaluation
87+
for (task in tasksQueue) {
88+
/**
89+
* Any unhandled exception here will pass through worker's boundary and will be properly reported.
90+
*/
91+
task.run()
92+
}
93+
}
94+
} catch (e: IllegalStateException) {
95+
// We deliberately ignore ISE here as they are expected
96+
// due to peculiarities of Workers API.
97+
// Unfortunately, race-free termination is unachievable by its current state,
98+
// see https://github.com/Kotlin/kotlinx.coroutines/issues/3578
9099
}
91100
}
92101

0 commit comments

Comments
 (0)