【发布时间】:2015-05-10 02:05:44
【问题描述】:
鉴于以下情况,匿名线程读取的 DoSomething 中 AValue 的值是否保证“可读”?即,我期望的价值?对我来说,我认为不会因为 DoSomething 在线程实际执行之前超出范围(即返回)(这可以通过意识到 x := 2 行总是在我的线程开始之前执行而很容易看出 - 尽管我猜线程所有的赌注都取消了,我的线程可能在 DoSomething 返回之前执行)。
我之所以问,是因为我在测试中从未遇到过 AValue 不等于 1(也就是传入的值)的场景,所以我想知道是否对过程和/或线程进行了一些隐式引用(再次不太可能,因为 CreateAnonymousMethod 只是创建了一个 TThread 后代(TAnonymousThread)的实例并调用我的匿名“执行”方法)。我猜测它是一样的,因为没有任何东西(在这个有限的场景中)覆盖了存储 AValue 的内存位置。
procedure TForm2.Button1Click(Sender: TObject);
var
x: Integer;
begin
x := 1;
DoSomething(x);
x := 2;// this line is only here for the purposes of placing a break point
end;
procedure TForm2.DoSomething(AValue: Integer);
begin
TThread.CreateAnonymousThread(
procedure
var
y: Integer;
begin
y := AValue;
if y = 1 then
MessageBox(0, 'Same', 'Value', MB_ICONINFORMATION or MB_OK)
else
MessageBox(0, 'Different', 'Value', MB_ICONINFORMATION or MB_OK)
end).Start;
end;
编辑 只是为了验证,我想知道在匿名线程的上下文中捕获局部变量是否安全。
【问题讨论】:
标签: multithreading delphi delphi-xe6