Home Race Condition when working with DLL and WideString
Reply: 1

Race Condition when working with DLL and WideString

Z.B.
1#
Z.B. Published in 2018-01-09 12:22:14Z

This question already has an answer here:

  • Unexpected Thread behaviour calling Delphi DLL 1 answer
  • DLL and class in multithreaded application 1 answer

I have faced following issue: When calling the DLL function in parallel from multiple threads I get the "EAggregateException: One or more errors occurred".

The minimal DLL example is:

library MyDLL;

uses
  System.SysUtils;

procedure MyUpper(const ASource: WideString; out AResult: WideString); stdcall;
begin
  AResult := String(ASource).ToUpper;
end;

exports
  MyUpper;

end.

The application which uses it:

program MyEXE;

uses
  System.SysUtils,
  System.Threading;

procedure MyUpper(const AText: WideString; out AResult: WideString); stdcall; external 'MyDLL.dll';

procedure Test;
var
  LLoop: TParallel.TLoopResult;
  LSync: IReadWriteSync;
begin
  LSync := TSimpleRWSync.Create;
  LLoop := TParallel.&For(1, 100000,
    procedure (AIndex: Integer)
    var
      LResult: WideString;
    begin
      MyUpper(AIndex.ToString, LResult);
    end);

  Writeln('Completed: ', LLoop.Completed);
end;

begin
  try
    Test;
  except
    on E: Exception do
      Writeln(E.ClassName + ': ' + E.Message);
  end;
  Readln;
end.

If in EXE I write following:

AResult := ASource;

Then the execution succeeds. But once I use any implicit/explicit string conversion it fails. How that could be? Each thread calls this method as an usual method with it's local stack and there is no shared variables (at least visible).

I don't use any shared memory manager as I am going to use the DLL from different programming languages.

What I am doing wrong?

Thank you in advance.

Z.B.
2#
Z.B. Reply to 2018-01-09 12:46:56Z

If the DLL is supposed to be used in the multithreaded environment then in initialization section of the library put the following line of the code:

IsMultiThread := True;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.311924 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO