threadvar和局部变量有什么区别 [英] What is the difference between a threadvar and a local variable

查看:69
本文介绍了threadvar和局部变量有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的线程中,我总是正常"声明局部变量,因此:

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?

推荐答案

首先,使用threadvar的代码是无效的语法. threadvar需要具有单位范围而不是本地范围.

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

局部变量

对函数的每次调用(包括从不同的线程和可重入的调用)都导致该函数的局部变量的不同实例.

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

线程局部变量

线程局部变量为进程中的每个线程具有单独的实例.变量的实例和线程之间存在一对一的映射.

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.

讨论

如果您的过程不是可重入的,并且它是唯一引用变量的过程,则局部变量和threadvar之间不会有语义上的区别–但是,如果可以使用局部变量,则它将应该是.

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.

在性能方面,threadvar比本地变量要慢,甚至可能在DLL上下文中也不起作用.

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

我的建议是尽可能使用局部变量.使用threadvar(或线程本地存储(TLS) (在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.

这篇关于threadvar和局部变量有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆