Jump to content
Sign in to follow this  
Martybartfast

Stopping a P4D Python thread

Recommended Posts

I have an application where a user can write and execute multiple Python scripts, each running in their own thread. I am using ThreadExecMode := emNewInterpreterOwnGIL; The code is now working great, and I can execute multiple Python scripts each in their own parallel thread. Awesome. 

 

Now I'd like the user to be able to click a Stop button for a thread, and have the associated Python script stop gracefully via Delphi code. Any way to do this? Does P4D check the thread Terminate property at all? I've tried testing with a simple Python For loop, and it didn't seem to stop it. Checked this forum, and didn't see anything. ChatGPT just gives nonsense (nothing new there!).

 

I could call the Windows APi TerminateThread function in a worst case, but that can cause all sorts of havoc. Any ideas on how to more gracefully stop a P4D thread?

Share this post


Link to post

TPythonThread is a TThread descendent.  But TThread.Terminate, does not stop threads.  Your code needs to check the value of Terminated.

 

Did you check Demo 33?https://github.com/pyscripter/python4delphi/blob/b6b63c7a2e94e027a52eac340d6fb38f084d5269/Demos/Demo33/SortThds.pas#L147C1-L158C5.  This works in that case because the python code releases the GIL regularly (when you call swap). 

 

Alternatively you can expose to your python scripts a Delphi variable that the python scripts check at short intervals.

In other words you have to engineer a way to stop the threads gracefully.  The same applies to standard Delphi threads.

Edited by pyscripter

Share this post


Link to post

Yes, I'd checked that demo out, and I read the idea of the Python code checking for termination. The challenge I have with my app is the end user will be able to write their own Python code, and maybe won't check for Terminate or a Delphi variable. If they do something silly like make an infinite loop without checking for terminate, then only option will be to crash out with TerminateThread I guess then.

 

Hummm, one idea I just thought of is maybe I can parse their code when it is downloaded to my app, and give warnings if they have any sort of loop without checks. 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×