无锁有界堆栈C++11原子学

Lock Free Bounded Stack C++11 atomics

本文关键字:C++11 原子学 堆栈      更新时间:2023-10-16

我正在考虑使用非常基本的有界(预分配)堆栈来以正确的 LIFO 顺序跟踪我的线程 ID。所以我想知道我的实现是否是线程安全的:

// we use maximum 8 workers
size_t idle_ids_stack[8];
// position current write happening at
std::atomic_uint_fast8_t idle_pos(0);
// this function is called by each thread when it is about to sleep
void register_idle(size_t thread_id) 
{
    std::atomic_thread_fence(std::memory_order_release);
    idle_ids_stack[idle_pos.fetch_add(1, std::memory_order_relaxed)] = thread_id;
}
// this function can be called from anywhere at anytime
void wakeup_one() 
{
    uint_fast8_t old_pos(idle_pos.load(std::memory_order_relaxed));
    std::atomic_thread_fence(std::memory_order_acquire);
    size_t id;
    do
    {
        if(old_pos == 0) return; // no idle threads in stack; exit;
        id = idle_ids_stack[old_pos-1];
    }
    while (!idle_pos.compare_exchange_weak(old_pos, old_pos-1, std::memory_order_acquire, std::memory_order_relaxed));
    // wakeup single thread
    signal_thread(id);
}

我不是无锁编程的专家,但我很确定你的代码不是线程安全的。

  1. 我们先来看看register_idle()

    这里可能发生的情况是 Thread1 递增idle_pos但在存储其 id 之前,另一个线程调用 wakeup_once 并使用过时的 id(在最坏的情况下甚至是无效的 on,因为数组尚未初始化)。我也看不出内存围栏的原因。

  2. wakeup_one()您有一个类似的问题(称为ABA问题):

    • 您加载当前idle_pos并根据id.
    • 另一个线程调用并完成wakeup_one(idle_pos减少)。
    • 另一个线程调用 register_idle ,这会再次将idle_pos增加到与以前相同的值。
    • 现在第一个线程恢复,认为idle_pos没有变化,并发出错误的线程信号

我可能弄错了,但我相信通常不可能基于数组创建完全无锁的堆栈,因为您必须在单个原子操作中做两件事:修改索引变量并在数组中存储或加载值。

除了这些逻辑错误之外,我强烈建议不要使用独立的内存围栏(它们使代码的可读性降低,甚至可能更昂贵)。此外,只有在确保程序与默认顺序正确后,我才会开始手动指定内存顺序。