Site icon Embarcadero RAD Studio, Delphi, & C++Builder Blogs

Learn About Using Threads Inside Python For A Windows Delphi App In This Sample

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-6742dab33bab3227734387/]

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

[crayon-6742dab33babe601352435/]

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-6742dab33bac1949416099/]

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

<strong>Python4Delphi Demo11<strong>

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