swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.3k stars 10.34k forks source link

Wrong error when passing `sending` closure to `TaskGroup` #76242

Open netural-philipp-gabriel opened 1 week ago

netural-philipp-gabriel commented 1 week ago

Description

The compiler produces an error when passing a sending closure to a TaskGroup. However if you pass the same closure to a Task this error does not pop up, which makes me think that TaskGroups behavior is not correct.

Reproduction

func send(
    operation: sending @escaping () async -> Void
) async {
    await withTaskGroup(of: Void.self) { taskGroup in
        taskGroup.addTask { // error: Passing closure as a 'sending' parameter risks causing data races between code in the current task and concurrent execution of the closure
            await operation()
        }
    }
}

Expected behavior

No compiler error.

Environment

Apple Swift version 6.0-dev (LLVM c3efe9282719c35, Swift b163fed2b3101e0) Target: arm64-apple-macosx14.0

Additional information

No response

jamieQ commented 1 week ago

relevant forum post: https://forums.swift.org/t/new-task-creation-apis/74322

netural-philipp-gabriel commented 3 hours ago

Hmm, not even capturing the closure as nonisolated(unsafe) seems to be working. I am getting the feeling I am holding it wrong. I pretty much just copied the parameter as it is used in TaskGroup.addTask 😕.