Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Writing a thread safe code in Delphi involves the basic care you would have in any other language, which means to deal with <strong>race conditions</strong>. A race condition happens when different threads access the <strong>same data</strong>. A good way to deal with that is to declare an instance of <strong>TCriticalSection</strong> and wrap the <em>dangerous</em> code in it.</p> <p>The code below shows a getter and a setter of a property that, by hypotesis, has a race condition.</p> <pre><code>constructor TMyThread.Create; begin CriticalX := TCriticalSection.Create; end; destructor TMyThread.Destroy; override; begin FreeAndNil(CriticalX); end; function TMyThread.GetX: string; begin CriticalX.Enter; try Result := FX; finally CriticalX.Leave; end; end; procedure TMyThread.SetX(const value: string); begin CriticalX.Enter; try FX := Value; finally CriticalX.Leave; end; end; </code></pre> <p>Notice the use of a single instance of <strong>TCriticalSection</strong> (<strong>CriticalX</strong>) to serialize the access to the data member <strong>FX</strong>.</p> <p>However, with Delphi you have an aditional consideration! VCL is not thread safe, so in order to avoid VCL race conditions, any operation that results in <strong>screen changing</strong> must run in the main thread. You get that by calling such a code inside a <strong>Synchronize</strong> method. Considering the class above, you should do something like this:</p> <pre><code>procedure TMyThread.ShowX; begin Synchronize(SyncShowX); end; procedure TMyThread.SyncShowX; begin ShowMessage(IntToStr(FX)); end; </code></pre> <p>If you have <strong>Delphi 2010</strong> or later, there is an easier way that makes use of anonymous methods:</p> <pre><code>procedure TMyThread.ShowX; begin Synchronize(procedure begin ShowMessage(IntToStr(FX)); end); end; </code></pre> <p>I hope this helps!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload