如何在Delphi中以原子方式设置布尔值?

时间:2018-05-21 14:38:24

标签: delphi

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

1 个答案:

答案 0 :(得分:3)

Delphi Boolean是一个字节值,不能与原子API一起使用,因为它们在32位值上运行。

您可以使用BOOL代替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));