gpt4 book ai didi

C++ 原子 : how to allow only a single thread to access a function?

转载 作者:行者123 更新时间:2023-12-03 06:51:28 26 4
gpt4 key购买 nike

我想编写一个一次只能由一个线程访问的函数。我不需要忙碌的等待,如果另一个线程已经在运行它,那么残酷的“拒绝”就足够了。这是我到目前为止想出的:

std::atomic<bool> busy (false);

bool func()
{
if (m_busy.exchange(true) == true)
return false;

// ... do stuff ...

m_busy.exchange(false);
return true;
}
  • 原子交换的逻辑是否正确?
  • 将两个原子操作标记为 std::memory_order_acq_rel 是否正确? ?据我了解,宽松的排序( std::memory_order_relaxed )不足以防止重新排序。
  • 最佳答案

    您的原子交换实现可能有效。但是尝试在没有锁的情况下进行线程安全编程总是充满问题并且通常更难维护。
    除非需要提高性能,否则 std::mutextry_lock()方法就是你所需要的,例如:

    std::mutex mtx;

    bool func()
    {
    // making use of std::unique_lock so if the code throws an
    // exception, the std::mutex will still get unlocked correctly...

    std::unique_lock<std::mutex> lck(mtx, std::try_to_lock);
    bool gotLock = lck.owns_lock();

    if (gotLock)
    {
    // do stuff
    }

    return gotLock;
    }

    关于C++ 原子 : how to allow only a single thread to access a function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64883986/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com