Skip to content
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

Prevent potential re-park when the unparking thread is too slow #2381

Merged
merged 1 commit into from Nov 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 13 additions & 1 deletion kotlinx-coroutines-core/jvm/src/scheduling/CoroutineScheduler.kt
Expand Up @@ -721,7 +721,19 @@ internal class CoroutineScheduler(
}
assert { localQueue.size == 0 }
workerCtl.value = PARKED // Update value once
while (inStack()) { // Prevent spurious wakeups
/*
* inStack() prevents spurious wakeups, while workerCtl.value == PARKED
* prevents the following race:
*
* - T2 scans the queue, adds itself to the stack, goes to rescan
* - T2 suspends in 'workerCtl.value = PARKED' line
* - T1 pops T2 from the stack, claims workerCtl, suspends
* - T2 fails 'while (inStack())' check, goes to full rescan
* - T2 adds itself to the stack, parks
* - T1 unparks T2, bails out with success
* - T2 unparks and loops in 'while (inStack())'
*/
while (inStack() && workerCtl.value == PARKED) { // Prevent spurious wakeups
if (isTerminated || state == WorkerState.TERMINATED) break
tryReleaseCpu(WorkerState.PARKING)
interrupted() // Cleanup interruptions
Expand Down
Expand Up @@ -77,4 +77,4 @@ class BlockingCoroutineDispatcherMixedStealingStressTest : SchedulerTestBase() {
cpuBlocker.await()
}
}
}
}