Skip to content

Use regular atomic operations for seqlock_object if std::atomic<T>::is_always_lock_free == true #19

@theuser27

Description

@theuser27

After a small test, I found that seqlock_object codegen can be improved for types that can be loaded/stored with a single atomic operation. Adding the following to the existing implementation would be sufficient.

template <typename T>
class seqlock_object
{
public:
    // extra flag to help the user, can be omitted
    static constexpr bool is_always_wait_free = std::atomic<T>::is_always_lock_free;

    // ...

    bool try_load(T& t) const noexcept
    {
        if constexpr (std::atomic<T>::is_always_lock_free)
        {
            t = data.load(std::memory_order_acquire);
            return true;
        }
        else {  /* ... */  }
    }

    void store(T t) noexcept
    {
        if constexpr (std::atomic<T>::is_always_lock_free)
        {
            data.store(t, std::memory_order_release);
        }
        else {  /* ... */  }
    }

private:
    struct non_atomic_holder
    {
        char data[sizeof(T)];
        std::atomic<std::size_t> seq = 0;
        static_assert(decltype(seq)::is_always_lock_free);
    };
    using holder = std::conditional_t<std::atomic<T>::is_always_lock_free, std::atomic<T>, non_atomic_holder>;
    holder data;
};

Perhaps even the memory ordering can be dropped to relaxed for this case since we only care about the data inside the atomics

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions