Release Python Global Interpreter Lock During Detection#384
Release Python Global Interpreter Lock During Detection#384christian-rauch merged 1 commit intoAprilRobotics:masterfrom
Conversation
Python's Global Interpreter Lock prevents other threads of a process from running. By releasing the GIL during the CPU intensive detection stage, other threads are allowed to run.
christian-rauch
left a comment
There was a problem hiding this comment.
I am not familiar with handing the GIL manual. Can this cause issues when you run apriltag_detect in Python in multiple threads using the same detector?
@christian-rauch I just finished some multithreaded testing and your hypothesis is correct. The program crashed when using the same detector object across multiple threads. I do think releasing the GIL provides a large enough benefit to warrant its inclusion. Maybe we add a note that the detect method is not thread safe? For those that do want to use a single detector object across multiple threads, they can use the Python threading module's lock objects. It's common practice to using locks in this way to synchronize access to shared objects. It also seems possible to implement the lock in C using the CPython lock interface. What do you think? Would updating the Python documentation noting that the detect method is not thread safe be enough? |
Thanks for testing this. Just to make sure, it does not crash with the commit just before your PR? Do you have a PoC to reproduce this with an example image?
Since we cannot know how users of the library use the bindings, this could now potentially break code in a hard to debug way. Adding documentation would only help new users of the bindings, if they read it at all. Is it possible to add this manual locking inside |
Correct. It does not crash when using the same detector object across multiple threads.
I don't have an example image. In Python, I simply created a detector,
I think so. It'll probably require 10-30 lines of code. I'll look into this. |
|
Hi Christian, I've created a PR here that implements a lock and acquires it before running detection. This prevents the crash mentioned earlier in this thread. Best, |
Summary:
This PR releases Python’s Global Interpreter Lock (GIL) during the CPU-intensive detection stage. This allows other threads in the Python process to run concurrently.
Details:
apriltag_detector_detect()is implemented purely in C and does not interact with Python objects.References:
Python docs: Releasing the GIL from extension code
Testing:
Changes are tested and work as intended.