代码之家  ›  专栏  ›  技术社区  ›  Cobra_Fast

如何获取compare exchange以接受我的变量?

  •  2
  • Cobra_Fast  · 技术社区  · 6 年前

    我正试图缓解库API(FUSE3)实现中一个简单预测功能的竞争条件,但我无法控制。要做到这一点,我想使用 std::atomic<>::compare_exchange_weak 尽可能早地在我的函数回调中:

    struct fdflag
    {
        // ...
        std::atomic<unsigned long long> read_seq_offset_pred;
        // ...
    };
    
    std::unordered_map<int, struct fdflag> fdflags;
    
    static int read(const char* path, char* buffer, size_t size, off_t offset, struct fuse_file_info* fi)
    {
        if (fdflags[fi->fh].read_seq_offset_pred.compare_exchange_weak(offset, offset + size)) // *
            fdflags[fi->fh].sequential_reads++;
        // ...
    }
    

    然而,gcc不允许我这样做,抱怨(在标记的行上 * ):

    错误:无法绑定类型为“std::\u atomic\u base::\uu int\u type&的非常量左值引用;{aka long long unsigned int&}'到类型为“std::\uu atomic\u base::\uu int\u type{aka long long unsigned int}的右值

    我试过使用 const_cast<off_t&>(offset) 但它给了我一个类似的错误消息。

    我如何获得 compare_exchange_weak(T&, T) 接受我的参数 (不会增加太多开销或破坏函数签名) ?

    1 回复  |  直到 6 年前
        1
  •  1
  •   NathanOliver    6 年前

    您的原子存储 unsigned long long . 这意味着 compare_exchange_weak compare_exchange_weak(unsigned long long&, unsigned long long) . 自从 off_t 是一个 long int 不能将其绑定到引用参数。您需要存储 关闭\u t 在原子变量中,将函数更改为 无符号长-长 ,或复制 offset 在一个 无符号长-长 在函数内部并将其传递给 比较\u exchange\u弱