mardi 10 août 2021

Queue.empty() is false, but the queue size is 0

I have a std::queue<std::vector<char>> GLOB_DATA_QUEUE; I'm using to tranfer data from one thread to another. I'm having a strange bug when trying to read from the queue. Here's my read code:

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;

During testing I'm running the above periodically without the provider thread running (so nothing is being input into the queue). What seems to happen is that .empty() keeps returning false, even when the queue is empty. Here's the output I get:

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

After a few repetitions it segfaults. Clearly the issue is calling .pop() on an empty queue, however what I can't figure out is why this is happening, and how I can fix it. There're no other threads even running at this point, so nothing else is ever touching the queue, and the mutex is in place at both ends anyway. Any ideas or pointers would be much appreciated.

Aucun commentaire:

Enregistrer un commentaire