Iyengar111 / NanoLog

Low Latency C++11 Logging Library
727 stars 186 forks source link

Try out linked list based data structure #7

Open Iyengar111 opened 8 years ago

Iyengar111 commented 8 years ago
struct LinkedList : public BufferBase
{
    LinkedList() : m_head(nullptr)
    {
    }

    struct Item
    {
        Item(NanoLogLine && logline_) : next(nullptr), logline(std::move(logline_))
        {}
        std::atomic < Item * > next;
        NanoLogLine logline;
    };

    void push(NanoLogLine && logline) override
    {
        Item * item = new Item(std::move(logline));
        Item * head = m_head.load(std::memory_order_relaxed);
        do
        {
            item->next = head;
        } while(!m_head.compare_exchange_weak(head, item, std::memory_order_release, std::memory_order_relaxed));
    }

    bool try_pop(NanoLogLine & logline) override
    {
        if (!m_read_buffer.empty())
        {
            logline = std::move(m_read_buffer.front());
            m_read_buffer.pop_front();
            return true;
        }
        Item * head = get_current_head();
        while (head != nullptr)
        {
            Item * next = head->next.load(std::memory_order_acquire);
            m_read_buffer.push_front(std::move(head->logline));
            delete head;
            head = next;
        };
        if (m_read_buffer.empty())
            return false;
        else
            return try_pop(logline);
    }

    Item * get_current_head()
    {
        Item * current_head = m_head.load(std::memory_order_acquire);
        while (!m_head.compare_exchange_weak(current_head, nullptr, std::memory_order_release, std::memory_order_relaxed));
        return current_head;
    }

private:
    std::atomic < Item * > m_head;
    std::deque < NanoLogLine > m_read_buffer;
};
damondd commented 7 years ago

any benchmark ?

Iyengar111 commented 7 years ago

Latency numbers were pretty much same with linked list so I did not pursue this further...