Is this using threadvar threadsafe?

I have a singleton that can be called in multiple threads.
I often look at the data quite often, and I need to cache the data so that I do not have to repeat the same search again and again.

I would like to do something similar to using static local variables, but in thread safe mode. I suspect the code below is waterproof. Is it correct?

type
  TPrevious = record
  public
    Fontname: string;
    FontSize: integer;
    Canvas: pointer;
    Width: integer;
  end;

threadvar Previous: TPrevious;

function TEditorOptions.GetEditorFontWidth(const Canvas: TCanvas): integer;
var
  Font: TFont;
//var  //static vars            <<-- static var != threadsafe
//  PreviousFontName: string = '';
//  PreviousFontSize: integer = 0;
//  PreviousCanvas: pointer = nil;
//  PreviousWidth: integer = 0;
begin
  {1: I'm assuming a managed threadvar is always initialized to Default(T)}
  if (Previous.Fontname <> '') then begin
      //Cache the values, so we don't recalculate all the time.
      //Caching is per thread, but that fine.
    if (SameText(Previous.FontName, FFontName)) and (Previous.FontSize = FFontSize)
       and (pointer(Canvas) = Previous.Canvas) then Exit(Previous.Width);
  end;
  Previous.Canvas := pointer(Canvas);
  Previous.FontName := FFontName;
  Previous.FontSize := FFontSize;
  Result:= SomeCalculation(Canvas, FFontName, FFontSize);
  ....
    Previous.Width:= Result;
  ....
end;

I have 2 questions:

A: Do I correctly assume that managed string flows, such as a string FontName, are always initialized to Default(T)(i.e. '')

B: Is this code completely thread safe / reusable?

+6
3
  • threadvar , string .

  • , threadvar ... string Previous.

  • threadvar, (, ).

  • : Previous.xxxxx : @Previous, ( with Previous do - ).

+5

vars, , . , , , .

, var. , , . .

+3

A, " threadvar threadsafe?". threadvar. .

, , . , , , , .


threadvar -. , threadvars, , . , , : .. , .

, , , - .

- .

  • .
  • A.
  • B.
  • @ .

, A , .

. Delphi , . , ( threadvar) . Delphi COW refcount, , ... , , , .

Canvas: Pointer . , . , , , .


  • - "". , .
  • , threadvars , . .
  • , . , Canvas , SomeCalculation.

. , . / , . NB. , .

+2

Source: https://habr.com/ru/post/1017250/


All Articles