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)

Most upvoted comments

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 of sleep_until(), it actually makes an unnecessary condition variable and mutex, and then uses SleepConditionVariableSRW() 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:

  • Internally Win32 uses a 64Hz tick (roughly 16ms per tick), though on some Windows versions, on some machines, this can change depending on things like the multimedia timer settings.
  • If you ask it to sleep for less than one tick, it seems to run a delay loop(!) I assume this behaviour is there for backwards compatibility (my guess is on 16-bit Windows some games were using Sleep() to do their timing?)
  • If you ask it to sleep for one tick or more, because of the way it tracks the tick count, it’s possible that you will wait for up to one tick less than you expect, depending on where you are in the present tick.

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.