Skip to content

Sleeping tasks high memory usage after being cancelled #60441

Open
@MarSe32m

Description

@MarSe32m

Describe the bug
Memory usage of a program, which cancels one million sleeping tasks, doesn't go down but stays at around 500-550MB.

Steps To Reproduce

public func sleepy() async throws {
    var tasks = [Task<Void, Never>]()
    for _ in 0..<1_000_000 {
        tasks.append(Task.detached {
            try? await Task.sleep(nanoseconds: UInt64(Int.max))
        })
    }
    
    for task in tasks {
        task.cancel()
        await task.value
    }
    tasks.removeAll()
}

@main
struct Main {
    public static func main() async throws {
        try await sleepy()
        // After running sleepy(), Xcode shows a memory usage of around 500-550MB
        try await Task.sleep(nanoseconds: 120_000_000_000)
    }
}

Expected behavior
The memory usage is expected to go down to around 30MB, since that is the amount of memory used for starting one million empty tasks.

Screenshots
sleep_cancel_memory_usage_bug

Environment

  • OS: macOS 12.5 Xcode Version 13.4.1, Ubuntu 20.04, Windows 10, Windows 11. Any platform I could get my hands on.
  • Swift version 5.6.2 and Swift Development Snapshot 2022-08-01

Additional context
I suspect the issue arises from the fact that enqueued sleep tasks stay in the system for the duration of the sleep even though the sleep is cancelled. And the culprit being the call to dispatch_after_f since there is no way currently to remove the enqueued block.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ConcurrencуArea → standard library: The `Concurrency` module under the standard library umbrellaTаskArea → standard library → Concurrency: The `Task` typebugA deviation from expected or documented behavior. Also: expected but undesirable behavior.concurrencyFeature: umbrella label for concurrency language featuresstandard libraryArea: Standard library umbrellaswift 5.6unexpected behaviorBug: Unexpected behavior or incorrect output

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions