Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

a new lock-free queue #79

Open
inie0722 opened this issue Jun 9, 2022 · 1 comment
Open

a new lock-free queue #79

inie0722 opened this issue Jun 9, 2022 · 1 comment

Comments

@inie0722
Copy link

inie0722 commented Jun 9, 2022

In theory, it is a queue without waiting, which supports multi-threaded reading and writing. Of course, the disadvantage is that the order of entering the queue may not be strongly ordered.

template<typename T, size_t N>
class queue
{
private:
    ring_buffer<T, N> value_;

    ring_buffer<atomic<size_t>, N> readable_flag_{0};
    ring_buffer<atomic<size_t>, N> writable_flag_{0};

    atomic<size_t> writable_limit_;
    atomic<size_t> readable_limit_;
public:
    queue() = default;
    ~queue() = default;

    void push(const T & val)
    {
        size_t index = writable_limit_.fetch_add(1);

        while (writable_flag_[index] != index / max_size())
            ;
        
        value_[index] = val;
        readable_flag_[index] = (index / max_size()) + 1;
    }

    void pop(T&val)
    {
        size_t index = readable_limit_.fetch_add(1);

        while(readable_flag_[index] != (index / max_size()) + 1)
            ;

        val = value_[index];
        writable_flag_[index] = (index / max_size()) + 1;
    }

    size_t max_size() const
    {
        return N;
    }

    size_t size() const
    {
        size_t writable_limit = writable_limit_;
        size_t readable_limit = readable_limit_;

        return writable_limit > readable_limit ? writable_limit - readable_limit : 0;
    }
};
@inie0722
Copy link
Author

c language implementation
mpmc_queue.h
mpmc_queue.c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant