我有一个std::queue<std::vector<char>> GLOB_DATA_QUEUE;
我用来将数据从一个线程传输到另一个线程。我在尝试从队列中读取数据时遇到了一个奇怪的错误。这是我阅读的代码(更新为完全独立):
#include <vector>
#include <queue>
#include <iostream>
// global data pipe object instaciation
// queue for data
std::queue<std::vector<char>> GLOB_DATA_QUEUE;
// global mutex for the thread
std::mutex GLOB_MUTEX;
// global condition variable for producer/consumer
std::condition_variable GLOB_CV;
int main(int argc, char *argv[])
{
// flow control for main logic loop
bool keep_running = true;
// this is the main loop we never plan to exit until shutdown
while(keep_running)
{
std::cout<<"servicing data queue"<<std::endl;
// sensor thread gets prioity, so if we can't have the mutex right now, go do something else
if(GLOB_MUTEX.try_lock())
{
std::cout<<"servicing data queue: got lock"<<std::endl;
std::cout<<"queue size: "<< GLOB_DATA_QUEUE.size() << std::endl;
if(!GLOB_DATA_QUEUE.empty()); // TODO - copy to local variable and release mutex before anything else
{
std::cout<<"servicing data queue: pop with queue size: " << GLOB_DATA_QUEUE.size() <<std::endl;
GLOB_DATA_QUEUE.pop();
}
std::cout<<"servicing data queue: unlocking"<<std::endl;
GLOB_MUTEX.unlock();
// TODO: do something with the data
}
std::cout<<"finished servicing data queue"<<std::endl;
}
}
在测试期间,我定期运行上述内容,而没有提供程序线程运行(因此没有任何内容输入到队列中)。似乎发生的是.empty()
即使队列为空,也会不断返回 false。这是我得到的输出:
servicing data queue
servicing data queue: got lock
queue size: 0
servicing data queue: pop with queue size: 0
servicing data queue: unlocking
finished servicing data queue
servicing data queue
servicing data queue: got lock
queue size: 4294967295
servicing data queue: pop with queue size: 4294967295
servicing data queue: unlocking
finished servicing data queue
重复几次后就会出现段错误。显然问题是调用 .pop()
在一个空队列上,但是我不明白为什么会发生这种情况,以及如何修复它。此时甚至没有其他线程在运行,因此没有其他线程接触队列,并且互斥体无论如何都在两端就位。任何想法或指示将不胜感激。
最佳答案
作为@G.M.在上面的评论中指出,替换
if(!GLOB_DATA_QUEUE.empty());
与
if(!GLOB_DATA_QUEUE.empty())
此外,add -Wall
to your compiler flags ,如果你说“请告诉我我是否做了明显错误的事情”,编译器可以并且会捕捉到这一点。
关于c++ - Queue.empty() 为 false,但队列大小为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68725621/