1

I'm currently having trouble when trying to close my application. As of now, my application currently spawns and thread that runs in a while loop (while True loop), while my main thread initializes and runs the UI in PyQT.

def main():

    group_size = 8 
    buffer_size = 4 
    app = QtGui.QApplication(sys.argv)
    dgui = DirectGui(group_size, buffer_size)
    engine = KCluster_Engine(group_size, buffer_size)
    dgui.set_engine_ref(engine)
    engine.assign_interface(dgui)
    thread = Thread(target = engine.start)
    thread.start()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

When I close out of my main window of my application in PyQT, the command that spawned the python script in the shell cannot be stopped, even with a ctrl-c.

What is the best way to deal with this behavior? When I close my application, I also want the spawned thread to stop, join and quit this process. How do I do this?

jab
  • 5,673
  • 9
  • 53
  • 84

2 Answers2

2

According to the Python Standard Library, you have two ways of killing your thread :

  • either you make it daemonic (thread.daemaon = True) and it will be killed without any possibility of proper cleaning
  • or you use a signaling method like Event that you test in appropriate places in you thread

But I think you should have a look to this older (but still of actuality ...) question in SO : Is there any way to kill a Thread in Python?

All this supposes that app.exec_() returns properly in your main thread.

Community
  • 1
  • 1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

If you make the thread daemonic it's going to stop after you exit the application. Put thread.daemon = True before starting it (if you do it after calling start an exception will be raised). It should work fine with threads from the threading module.

Mátyás Kuti
  • 742
  • 6
  • 8