What is the difference between a threadvar and a local variable

假如想象 提交于 2019-12-03 12:32:36

问题


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?


回答1:


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.




回答2:


By using ThreadVar keyword, each thread is given a separate instance of each variable, thereby avoiding data conflicts, and preserving thread independence.

Also you do not need to protect your threadvar variables in critical sections, due to the fact that are local to the thread.

best regards,
Radu



来源:https://stackoverflow.com/questions/5180933/what-is-the-difference-between-a-threadvar-and-a-local-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!