delphi - 如何在 Delphi 中原子地设置布尔值?
问题描述
AtomicExchange 需要一个 Integer 或 NativeInt 变量,但我如何使用它(或类似的东西)以线程安全的方式设置一个布尔值 - 或者是否需要它?
解决方案
DelphiBoolean
是一个字节值,不能与 Atomic API 一起使用,因为它们对 32 位值进行操作。
您可以使用 aBOOL
代替,它是一个 32 位布尔值,如下所示:
var
b: bool;
begin
b := False;
// true
AtomicIncrement(Integer(b));
// false
AtomicDecrement(Integer(b));
但是,递增有点危险,因为将其递增两次(类似于两次分配 True )并递减一次意味着该值 > 0 因此仍然True
.
另一种可能是这样的:
// false
AtomicExchange(Integer(b), Integer(False));
// true
AtomicExchange(Integer(b), Integer(True));
推荐阅读
- c# - 防止用户附加到 MS-Office 进程的开发者运行实例
- c# - 根据元素相似性列表对项目进行分组
- python - Python throwing ValueError: is not in list 尽管它在列表中
- python - Python:如何删除超过 3 个月的名为垃圾桶的文件夹
- c# - 为表设置主键?
- google-kubernetes-engine - 在 GKE 上跨集群按名称解析 Kubernetes 服务
- vue.js - Vue.js 呈现不同的表单字段
- prolog - 列表中从 N 到 N 的双元素,代码给出 false
- azure - 在 Azure App 服务中创建 Webapp 时出现使用错误
- c# - 如何将最大 SortOrder 作为 int 获得?