首页 > 解决方案 > 如何在 Delphi 中原子地设置布尔值?

问题描述

AtomicExchange 需要一个 Integer 或 NativeInt 变量,但我如何使用它(或类似的东西)以线程安全的方式设置一个布尔值 - 或者是否需要它?

标签: delphi

解决方案


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));

推荐阅读