Skip to content

Accessing @Shared in a Dependency can result in a Deadlock #149

@stefandraskovits-aaa

Description

@stefandraskovits-aaa

Description

If a Dependency is accessing @Shared while a @Shared is being accessed on another Thread can lead to a deadlock.

I think the reason for that is that the Dependency gets the lock in CachedValues.
Concurrently on another thread @Shared gets the lock of PersistentReferences.
During the initialization of a _PersistentReference (while holding the "SharedLock") Dependencies ares accessed -> which required the lock of CachedValues, which is currently locked by a Dependency, which again wants to access an @Shared property => Deadlock

Here the screenshots of the two threads trying to get access to the locks.

Image
Image

Checklist

  • I have determined whether this bug is also reproducible in a vanilla SwiftUI project.
  • If possible, I've reproduced the issue using the main branch of this package.
  • This issue hasn't been addressed in an existing GitHub issue or discussion.

Expected behavior

No deadlock or a clarification when it is safe to use or access @shared inside of a dependency.
In the end the last prints should be executed.

Actual behavior

A deadlock which potential effects the main thread, which leads to the termination of the app.
The print is not executed.

Reproducing project

I have added two xcode projects where I can reproduce this behavior.
The first one Locking test has altered the swift-sharing dependency to make the race condition easily reproducible. I introduced a Thread.sleep(forTimeInterval: 1.0) in the final class PersistentReferences: @unchecked Sendable, DependencyKey {

In the second project Locking test2 I am using the latest release of swift-sharing (without altering anything). In that version the timing / scheduling might be important (tweaking the Thread.sleep(forTimeInterval: 0.001) before the dependency is accessed, number of @Sharedaccessed ) - nevertheless it is still reproducible on my end.

Shared-Locking.zip

Sharing version information

2.4.0

Destination operating system

iOS 18.3.1

Xcode version information

Version 16.2 (16C5032a)

Swift Compiler version information

swift-driver version: 1.115.1 Apple Swift version 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1)
Target: arm64-apple-macosx15.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions