【问题标题】:Lock Free Bounded Stack C++11 atomics无锁有界堆栈 C++11 原子
【发布时间】:2015-09-04 10:46:44
【问题描述】:

我正在考虑使用非常基本的有界(预分配)堆栈来以正确的 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);
}

【问题讨论】:

标签: c++ multithreading c++11 stack lock-free


【解决方案1】:

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

  1. 我们先来看看register_idle()

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多