Delphi的简单类型线程是否安全? [英] Are Delphi simple types thread safe?

查看:151
本文介绍了Delphi的简单类型线程是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我宣布了两个全局变量:

  var 
gIsRunning:Boolean = False;
gLogCounter:Integer = 0;

这些变量只能写在主线程中,并且读入其他线程。在这种情况下,这些变量线程是否安全?

解决方案

你可能在说原子变量。整数和布尔变量是原子的。布尔(字节)始终是原子,整数(32位)是原子的,因为编译器正确对齐它们。



原子性意味着任何读或写操作都被执行为整个。如果线程A同时执行相同数据的原子写入和线程B原子读取,线程B读取的数据总是一致的 - 线程B读取的某些位是不可能从当前写操作获得的,但是原子性并不意味着线程的安全性 - 你可以很容易地用原子变量编写不安全的代码。变量本身不能是线程安全的 - 只有整个代码可以(或不是)线程安全。


I declared two global variables:

var
  gIsRunning: Boolean = False;
  gLogCounter: Integer = 0;

These variables are written only in the main thread, and read in other threads. In this case, are these variables thread safe?

解决方案

You are probably saying about atomic variables. Integer and Boolean variables are atomic. Booleans (bytes) are always atomic, integers (32-bits) are atomic because the compiler properly aligns them.

Atomicity means that any read or write operation is executed as a whole. If a thread A executes atomic write and a thread B atomic read of the same data at the same time, the data read by thread B is always consistent - it is impossible that some bits read by thread B are obtained from the current write operation and some bits from the previous write (by thread A)

But atomicity does not mean thread safety - you can easily write unsafe code with atomic variables. A variable itself cannot be threadsafe - only a code as a whole can be (or not) threadsafe.

这篇关于Delphi的简单类型线程是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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