Skip to content
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

Synchronized containers deadlock when reading from multiple threads #547

Open
dalemyers opened this issue Mar 5, 2024 · 0 comments
Open

Comments

@dalemyers
Copy link

If you try and read a container from multiple threads, even if you've called .synchronize(), you will run into a dead lock issue. The following code is an example:

let container = Container()

_ = container.register(Foo.self) { _ in
    Thread.sleep(forTimeInterval: 100.0)
    return Foo()
}.inObjectScope(.container)

_ = container.register(Bar.self) { _ in
    return Bar()
}.inObjectScope(.container)

DispatchQueue.global().async {
    _ = container.synchronize().resolve(Foo.self)
}

// Allow the dispatch to happen
Thread.sleep(forTimeInterval: 0.5)

// This will block for 100 seconds
_ = container.synchronize().resolve(Bar.self)

The problem stems from the use of NSRecursiveLock. This lock allows multiple read acquisitions on the same thread, but will block across different threads.

@dalemyers dalemyers changed the title Synchronized containers are prone to deadlock when reading from multiple threads Synchronized containers deadlock when reading from multiple threads Mar 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant