Skip to content
Advertisement

PyQt5: Python crashes with SIGSEGV *sometimes* when sending pixmap via a signal from another thread

Background and Issue

I am trying to process streaming data from a camera. Python keeps crashing with this message though:

JavaScript

The crash happens sometimes while emitting the signal containing an image.

My code, shown below, follows this process:

  1. A QObject named CameraThread is instantiated within the GUI and is run by a QThread.
  2. CameraThread instantiates a class IngestManager and gives it to the data source. The data source will call IngestManager‘s write() method repeatedly, providing data.
  3. The worker threads process the data and sends it back to IngestManager via a callback method frame_callback
  4. IngestManager emits the signal. This is where it crashes sometimes.

What I’ve tried / Observations

I tried several ways to fix it, including passing the pyqtSignal to the worker threads themselves. I also reckon that sometimes, the threads finish and emit at the same time, but I’m not sure how to tackle this.

The crash happens much sooner the more I interact with the GUI, such as rapidly pressing a dummy button. It almost never happens if I don’t interact with the UI (but it still happens). I think I may need lock of some sorts.

How do I start solving this problem?


This is the code that connects to the data source, processes the data, and emits the signal.

JavaScript

And this is how the code above is used:

JavaScript

Advertisement

Answer

Firstly, it’s not safe to use QPixmap outside the main thread. So you should use QImage instead.

Secondly, ImageQt shares the buffer from the Image passed to it. So if the buffer is deleted while the Qt image is still alive, a crash will very likely ensue. You might need to copy the Qt image to prevent this happening if you can’t keep hold of the PIL image for long enough.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement