[fpc-devel] Comparison FPC 2.6.2 - Delphi 7

Sven Barth pascaldragon at googlemail.com
Thu Mar 7 21:15:50 CET 2013


On 06.03.2013 14:36, Sven Barth wrote:
> Am 06.03.2013 14:29, schrieb Michael Schnell:
>> On 03/06/2013 01:43 PM, Sven Barth wrote:
>>>
>>>> And how does one the "current" TThread?
>>> Since a few weeks: TThread.CurrentThread ;)
>>>
>>
>> This does in fact use a threadvar:
>>
>> threadvar
>>   { the instance of the current thread; in case of an external thread
>> this is
>>     Nil until TThread.GetCurrentThread was called once (the RTLs need
>> to ensure
>>     that threadvars are initialized with 0!) }
>>   CurrentThreadVar: TThread;
>>
>>
>> and (unless the compiler optimizes this out) even accesses it twice:
>>
>>
>>   if not Assigned(CurrentThreadVar) then
>>     CurrentThreadVar := TExternalThread.Create;
>>   Result := CurrentThreadVar;
>>
>>
>> From within the TThread object, simply using Self seems more
>> appropriate unless there is a chance that the same TThread instance is
>> used for multiple OS-Threads. I don't know if/how this is possible.
>>
>> From "outside" I feel that AnyThread.GetCurrentThread does not make
>> much senses.
>>
>> When doing "TThread.GetCurrentThread" as a class function I think I
>> should get "self" of same when I am in the code that is called from
>> "Execute" of some TThread instance. I  don't see what I want to see
>> when I'm not.
>>
>> The code seems to try to avoid the case that a no TThread instance
>> when  GetCurrentThread is called as a a class function. I don't know
>> if/how this is sensible.
>>
>> Using CurrentThread only seems sensible within the the code of a
>> component that has been called by the code of a TThread instance. But
>> here using an appropriate back-link property can easily be used to
>> avoid accessing the threadvar. (or using  CurrentThread once to set a
>> property  and then just accessing same.) But this of course needs to
>> be done in user code and the RTL can't force it.
>
> The TThread.CurrentThread is mainly for access in functions that don't
> get passed a "TThread" instance and to also get a "TThread" instance for
> threads not created by the RTL (the "TExternalThread.Create" line
> above). Don't forget that TThread.CurrentThread is a class
> property/function, so you can't access Self.
>
> We could optimize it like this:
>
> === code begin ===
>
> Result := CurrentThreadVar;
> if not Assigned(Result) then begin
>    Result := TExternalThread.Create;
>    CurrentThreadVar := Result;
> end;
>
> === code end ===
>
> So that in the normal case only one access to the threadvar is used.

I've implemented this optimization in r23706. So in the normal case the 
threadvar is only read once and in the worst case it's read once and 
written once.

Regards,
Sven




More information about the fpc-devel mailing list