Search code examples
c++qtatomic

Qt atomic int get and immediately set


I need to get current value stored in atomic int (QAtomicInteger I suppose) and immedeately reset it to 0. This to be the counter. While one thread incrementing this counter, I am to get the value in another thread at some moment and immediately reset this counter to be sure every increment is counted.

How can I do this?


Solution

  • Solution

    In order to get the value stored in a QAtomicInt and immediately assign another value to it, use QAtomicInteger::fetchAndStoreRelaxed.

    Note: You could also use another of the available fetchAndStore methods, depending on the memory ordering you need.


    Example

    As for the bigger picture of how you want to use this value, I have prepared an example for you.

    #include "Counter.h"
    #include <QTimer>
    
    Counter::Counter(QObject *parent) :
        QObject(parent),
        m_counter(new QAtomicInt()),
        m_counting(false)
    {
    
    }
    
    int Counter::setValue(int value) const
    {
        return m_counter->fetchAndStoreRelaxed(value);
    }
    
    void Counter::countFrom(int value, int delay)
    {
        if (m_counting)
            return;
    
        m_counting = true;
        m_counter->store(value);
    
        auto *timer = new QTimer();
    
        timer->start(delay);
    
        connect(timer, &QTimer::timeout, [this](){
            m_counter->operator ++();
            changed(m_counter->load());
        });
    }
    

    The full example consisits of one thread incrementing a counter. It also allows to read the value of the counter on a click of a button, immediately resetting the counter to zero.

    The complete code of this example could be downloaded from GitHub.