Skip to content

Mutex allows to return the protected Value instance without reinitialization #81274

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

Open
NSFatalError opened this issue May 3, 2025 · 1 comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels

Comments

@NSFatalError
Copy link

Description

From the Mutex proposal, following code is unsafe and it's correctly diagnosed:

import Synchronization

open class NonSendable {}

final class Store: Sendable {
    private let lock = Mutex(NonSendable())

    func referenceCurrentState() -> NonSendable {
        var reference: NonSendable!
        lock.withLock { state in
           reference = state
           // Expected error: 'inout sending' parameter 'state' cannot be task-isolated at end of function
        }
        return reference
    }
}

The same diagnostic however isn't applied when we simply return the protected state from the closure passed to withLock method (see reproduction).

Reproduction

import Synchronization

open class NonSendable {
    func mutate() { ... }
}

final class Store: Sendable {
    private let lock = Mutex(NonSendable())

    func returnCurrentState() -> NonSendable {
        lock.withLock { state in
            return state 
            // No error!
        }
    }
}

let store = Store()
await withTaskGroup { group in
    for _ in 0 ..< 1000 {
        group.addTask {
            store.returnCurrentState().mutate()
        }
    }
}

Expected behavior

Returning inout sending value should require reinitialization.

Environment

Apple Swift version 6.1 (swift-6.1-RELEASE)
Target: arm64-apple-macosx15.0

Additional information

No response

@NSFatalError NSFatalError added bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels labels May 3, 2025
@jamieQ
Copy link
Contributor

jamieQ commented May 5, 2025

note: this looks like it may be a regression in 6.1+ as the 6.0 compiler did appear to diagnose this case: https://swift.godbolt.org/z/vMW18nd84

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels
Projects
None yet
Development

No branches or pull requests

2 participants