ronaldoussoren / pyobjc

The Python <-> Objective-C Bridge with bindings for macOS frameworks
https://pyobjc.readthedocs.io
548 stars 46 forks source link

tp_dealloc & threads #526

Open ronaldoussoren opened 1 year ago

ronaldoussoren commented 1 year ago

There is no guarantee as to which thread is used to deallocate an object. Especially with cycles deallocation could happen on a second thread that happens to break the reference cycle by running the GC.

This can be a problem if "MainActor" proxy objects happen to be deallocated on a secondary thread and Python's reference is the last one that keeps the ObjC object alive.

In practice I haven't run into this problem yet. I've created this issue to ensure I don't forget to look into this in the future. It might be possible to arrange for calls to -release in the deallocation of proxy objects to happen on the main thread or the thread that created the proxy object. This needs to be designed and verified to make sure this doesn't holes were ObjC objects can be reallocated on the wrong thread (for example through autorelease pools)

Also research if there are frameworks that require handling objects on specific threads other than the main thread. One possible example is CoreData, AFAIK that framework can be used on multiple threads, but does require per-thread contexts.

Open question: what to do if the thread that created the proxy no longer exists when the proxy needs to release its reference tot the Objective-C object.

ronaldoussoren commented 1 year ago

Any implementation work this needs thorough testing, both to show the problem in the current implementation and to show that the changed implementation actually fixes the issue.