-
Notifications
You must be signed in to change notification settings - Fork 70
Description
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.
Checklist
- I have determined whether this bug is also reproducible in a vanilla SwiftUI project.
- If possible, I've reproduced the issue using the
mainbranch 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.
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
