Martybartfast 2 Posted 19 hours ago 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
pyscripter 796 Posted 18 hours ago (edited) 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 18 hours ago by pyscripter Share this post Link to post
Martybartfast 2 Posted 6 hours ago 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