Guest Posted January 15, 2023 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
Soulflesh 1 Posted January 15, 2023 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
David Heffernan 2345 Posted January 15, 2023 You should read about the Python GIL which is liable to be an issue Share this post Link to post
pyscripter 689 Posted January 16, 2023 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