compare_exchange_weak

实现无锁数据结构的基础是CAS:Compare & Set,或是 Compare & Swap。CAS用C语言描述的代码(来自 Wikipedia Compare And Swap)

int compare_and_swap (int* reg, int oldval, int newval) 
{
  ATOMIC();
  int old_reg_val = *reg;
  if (old_reg_val == oldval) 
     *reg = newval;
  END_ATOMIC();
  return old_reg_val;
}

大体的意思就是旧值跟当前对象值相等,就把新值给到当前对象,再返回当前对象的原始值。

扩展到atomic中的compare_exchange_weak函数

bool compare_exchange_weak (T& expected, T val,
           memory_order sync = memory_order_seq_cst) volatile noexcept;
bool compare_exchange_weak (T& expected, T val,
           memory_order sync = memory_order_seq_cst) noexcept;
bool compare_exchange_weak (T& expected, T val,
           memory_order success, memory_order failure) volatile noexcept;
bool compare_exchange_weak (T& expected, T val,
           memory_order success, memory_order failure) noexcept;
expected相当于oldval,val相当newval,调用compare_exchange_weak函数的对象就是相当于reg。

如果reg的值==expected的值,则reg的值=val,且返回true;否则,返回false。

用这么复杂的函数原因就是线程安全。

你可能感兴趣的:(C/C++)