std::list::empty() returns true even though list is filled

158 views Asked by At

I am having issues in a code having structure similar to the following minimum example. There is only one instance of MainClass. It makes new instance of Classlet on each call to its MainClass::makeclasslet()

I have multiple classlets writing to a single list buffer. After some time I need to copy/ dump the values from list buffer (FIFO).

The problem is that I am getting the following output in MainClass::clearbuffer()

>>>>>>>>>> 704 >>>>>>>>>>>>>>>>>>> Buffer size: 65363..... 1

I am unable to understand why the std::list::empty() returns true even when the buffer is locked with an atomic bool flag. I have tried moving the call to clearbuffer() (in addval()) to the main application thread so that not each Classlet event calls clearbuffer(). I have also tried adding delay QThread::msleep(10); after setting busy = true;. But some time after the application starts, I am getting the output shown above. Instead of popping all 65363+704 values in the list, it only popped 704 and broke the loop on list::isempty() being true (apparently).

class MainClass : public QObject {
Q_OBJECT

    private:
        std:: list<int> alist;
        std::atomic<bool> busy;
    MainClass() {
        busy = false;
    }
    ~MainClass() {
        // delete all classlets
    }
    void makeclasslet() {
        Classlet newclasslet = new Classlet();
        // store the reference
    }
    void addval(int val) {
        alist.push_back(val);
        if (alist.size() > 100)
        {
            if (!busy)
            {
                clearbuffer();
            }
        }
    }
    void clearbuffer() {
        if (!busy)
        {
            busy = true;

            int i = 0;
            while (!alist.empty())
            {
                i = i + 1;
                // save alist.front() to file
                alist.pop_front();
            }
            printf(">>>>>>>>>> %d >>>>>>>>>>> Buffer size: %d ..... %d\n", i, m_lstCSVBuffer.size(), m_lstCSVBuffer.empty());
            busy = false;
        }
    }
}
class Classlet {
    private:
        Mainclass* parent;
    void onsomeevent(int val) {
        parent->addval(val);
    }
}

I am using qt5.9 on Ubuntu 18.04. GCC/ G++ 7.5.0

0

There are 0 answers