realm-swift: Intermittent Crash when using realm on background thread (v5.3.1)
Goals
Write to realm from background thread without crash
Steps for others to Reproduce
Occasionally (and seemingly randomly) realm will throw an exception for "Realm accessed from incorrect thread." during beginWriteTransaction.
We are creating a new realm instance on the current thread and it is within an autorelease pool. When this exception is occurring the doWrite closure is not reached (the exception occurs at beginWriteTransaction).
We have also tried using the new queue-confined Realm init but experienced the same crash, also randomly.
After extensive debugging it seems that something must be going wrong with the thread check, or the underlying cache is returning the wrong instance intermittently.
Any ideas on a potential solution?
Code Sample

Version of Realm and Tooling
Dependency manager: SPM
Realm-cocoa 5.3.1 Realm 5.3.1 Realm-core 6.0.11
Xcode version: 11.5 iOS/OSX version: 13.5
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 7
- Comments: 25 (4 by maintainers)
I’ve successfully reproduced a case which would cause spurious incorrect thread exceptions and am working on a fix.