Jump to content
Sign in to follow this  
uefi

How USE Python4Delphi in multithreads

Recommended Posts

Hello, I can't use PYTHON4DELPHI in threads, errors keep popping up:

 

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, pythonengine, System.syncobjs;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
cs:TcriticalSection;
threads:integer;
begin
cs:=TcriticalSection.Create;
for threads :=0 to 5 do
TPythonThread.CreateAnonymousThread(
procedure
var
val:string;
Writer:TStreamWriter;
PythonEngine1:TPythonEngine;
begin
cs.Enter;
val:='';
cs.Leave;
PythonEngine1:=TPythonEngine.Create(nil);
PythonEngine1.LoadDll;
PythonEngine1.ExecString('fun=("Hello World")');
val:=( 'Value = ' + PythonEngine1.EvalStringAsStr('fun')  );
FreeAndNil(PythonEngine1);
form1.Memo1.Lines.Add(val);
TPythonThread.Synchronize(nil,
procedure
begin
Writer := TStreamWriter.Create(Extractfilepath(paramstr(0))+'TEST'+'.txt',
true, TEncoding.Ansi);
Writer.WriteLine(val);
Writer.Free;
end);
end).Start;
end;
end.

 

Share this post


Link to post

Hi uefi,

 

have a look at Running Python scripts in threads - Python4Delphi - Delphi-PRAXiS [en] (delphipraxis.net).

Unfortunately, this still does not work in the form of true parallelism at the moment. Only the pseudo Python thread parallelism. From my point of view, there is currently only the possibility/attempt to multiply the Python dlls and load them per thread.

 

Bets regards

Share this post


Link to post
8 hours ago, uefi said:

I still don’t understand how you did it and where to insert it
Py_Begin_Allow_Threads; and Py_End_Allow_Threads;

Use Demo 33 as a guide.  As @David Heffernan said running python in threads is not trivial and unlikely to save you time. 

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  

×