swift: Task.sleep() sleep too long on Windows
Description
No response
Reproduction
@main
public struct App {
public static func main() async throws {
let clock = ContinuousClock.continuous
let dur = try await clock.measure {
try await Task.sleep(for: .seconds(0.1))
}
print("Slept for: \(dur)")
}
}
Output:
Slept for: 64.1733749 seconds
Expected behavior
Task sleep for 0.1 second.
Environment
Swift version 5.10-dev (LLVM 7c3b53ecaad54fb, Swift ebaa8c65f94e6a1) Target: x86_64-unknown-windows-msvc
Additional information
No response
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 16 (14 by maintainers)
Concurrency uses libc++'s
std::this_thread::sleep_until()function to sleep, which in turn on Windows calls into the Win32 API directly without very much adjustment. In the case ofsleep_until(), it actually makes an unnecessary condition variable and mutex, and then usesSleepConditionVariableSRW()to do the actual sleeping, after converting the time to sleep in nanoseconds into a number of milliseconds.The Win32 API’s sleep behaviour is highly unusual; I’m not sure why it would cause this degree of over-sleeping, but to give a brief explanation of what it appears to do:
Sleep()to do their timing?)The Swift runtime’s own wait code deliberately adds 16ms to every sleep in order to ensure that we wait for at least the specified duration, since that’s the behaviour everyone expects (normally on other systems you would never wait for less than the time you asked for, unless a signal is delivered). libc++ doesn’t do that, though, and Concurrency is using libc++'s code, not the runtime’s code.
Now, even though all of this is very odd, as I say, I don’t see why it would result in over sleeping. If the sleep duration was very short, it might, but for longer sleep durations on an un-loaded machine I’d expect under sleeping to occur. It may be that the combination of under-sleeping and the loop in
claimNextFromCooperativeGlobalQueue()combine somehow to produce this effect, not sure.