Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a threadvar and a local variable

In my threads, I always declare local variables "normally", thus:

procedure TMyThread.Execute ;

var
   i : integer ;

begin
i := 2 ;

etc, If I declare them thus:

procedure TMyThread.Execute ;

threadvar
   j : integer ;

begin
j := 2 ;

how does execution/code generation/speed/thread-safety alter?

like image 962
rossmcm Avatar asked Mar 03 '11 12:03

rossmcm


People also ask

What is the difference between a local variable and a global variable?

A global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition.

What is global and local variable in C++?

A global variable is valid from the point it is declared to the end of the program. A local variable's scope is limited to the block where it is declared and cannot be accessed (set or read) outside that block.

What is difference between local and global scope in JavaScript?

JavaScript variables have only two scopes. Global Variables − A global variable has a global scope which means it can be defined anywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

What is local variable and global variable in python?

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.


1 Answers

Well for a start the code with the threadvar is invalid syntax. A threadvar needs to have unit scope rather than local scope.

Local variable

Each invocation (including from different threads, and re-entrant calls) of a function results in different instances of that function's local variables.

Thread local variable

A thread local variable has separate instances for each thread in the process. There is a one-to-one mapping between instances of the variable and threads.

Discussion

If your procedure is not re-entrant, and it is the only procedure that refers to the variable then there will be no semantic difference between a local variable and a threadvar – but if a local variable can be used then it should be.

In terms of performance the threadvar is slower than a local variable and may not even work in the context of a DLL.

My recommendation is to use a local variable wherever it is possible to do so. Use a threadvar (or Thread Local Storage (TLS) when in a DLL) if you need a variable of global scope that has a single instance per thread. However, such need is rare and has the severe downside that thread local variables have many of the same drawbacks as true global variables.

like image 176
David Heffernan Avatar answered Oct 21 '22 12:10

David Heffernan