Site icon Python GUI

Learn How To Build A Powerful Python Threading System For Your Python Windows GUI Apps

We know Delphi supports Multithreading. Multithreading in Python can be achieved using Python Module Threading. However, In a use case like Delphi Application embedding Python(Python4Delphi) or CPython, the interpreter is not fully thread-safe. In order to support multi-threaded Python programs, there’s a global lock, called the global interpreter lock or GIL, that must be held by the current thread before it can safely access Python objects. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines.

Some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally-intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O. More Details here. This post will guide you on how to evaluate several python functions concurrently using Python4Delphi TPyDelphiThread.

Python4Delphi Demo11 Sample App shows how to achieve concurrency(using more interpreters) inside Python. You can find the Demo11 source on GitHub.

Prerequisites: Download and install the latest Python for your platform. Follow the Python4Delphi installation instructions mentioned here. Alternatively, you can check out this video Getting started with Python4Delphi.

Components used in Python4Delphi Demo11 App:

You can find the Python4Delphi Demo11 sample project from the extracted GitHub repository ..Python4DelphiDemosDemo11.dproj. Open this project in RAD Studio 10.4.1 and run the application.

Implementation Details:

In this Sample, one interpreter Button uses an emNewState(single interpreter with new state and upon execution completion, restores the thread state) ThreadExecMode and three interpreter button use an emNewInterpreter (same as a new state but with new interpreter fully initialized) ThreadExecMode to Execute.

[crayon-6628cd0f1c660530704744/]

When all the thread is executed the OwnThreadState is restored as shown below.

[crayon-6628cd0f1c669345266875/]

On Clicking one interpreter or three interpreter button, the three thread is initialized and executes python script by the TSortThread.ExecuteWithPython procedure as shown below.

[crayon-6628cd0f1c66b050100259/]

Upon execution the 3 PaintBox’s is get updated by the TSortThread.VisualSwap procedure.

Python4Delphi Demo11

Hope this helps to understand threading inside python for a Delphi Application.

Head over and find out more about building Windows Apps with Python4Delphi on GitHub.

Exit mobile version