首页 > 解决方案 > 即使列表已填满,std::list::empty() 也会返回 true

问题描述

我在结构类似于以下最小示例的代码中遇到问题。MainClass 只有一个实例。它在每次调用 MainClass::makeclasslet() 时创建新的 Classlet 实例

我有多个小类写入单个列表缓冲区。一段时间后,我需要从列表缓冲区(FIFO)中复制/转储值。

问题是我在 MainClass::clearbuffer() 中得到以下输出

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

我无法理解为什么 std::list::empty() 即使缓冲区被原子 bool 标志锁定也会返回 true。我已经尝试将对 clearbuffer() 的调用(在 addval() 中)移动到主应用程序线程,以便不是每个 Classlet 事件都调用 clearbuffer()。我也尝试QThread::msleep(10);在设置后添加延迟busy = true;。但是在应用程序启动一段时间后,我得到了上面显示的输出。它不是弹出列表中的所有65363+704值,而是弹出并704打破循环(显然)。list::isempty()true

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);
    }
}

我在 Ubuntu 18.04 上使用 qt5.9。GCC/G++ 7.5.0

标签: c++qtqt5.9

解决方案


推荐阅读