简体   繁体   中英

C++ :deque iterator not dereferencable

I'm trying to do a simple program to learn about Threads and concurrency in C++. I've created a template class named MyQueue which implements a queue and some variables to handle the synchronization of threads.

The class has just two functions to get and put items from the queue and one function to close the queue and avoid further access.

The program compiles just fine but when debugging it gets the following error:

Expression: deque iterator not dereferencable

This can happen no matter what the thread is doing, if get or put items.

Here is the code:

template <class T> class MyQueue{
queue<T> myqueue;
int N;
bool open;
mutex m,m_open;
condition_variable cv,cv2;

public:
MyQueue(int size){
    N=size;
    open=true;
}

bool isOpen(){ 
    lock_guard<mutex> lg(m_open);
    return open;
}

void close(){
    lock_guard<mutex> lg(m_open);
    open=false;
    cv.notify_all();
    cv2.notify_all();
}

bool get(T &t){
    if(isOpen()==false)return false;
    if(myqueue.size()>0){
        {
            lock_guard<mutex> lg(m);
            t=myqueue.front();
            myqueue.pop();
            cv.notify_one(); 
        }
    }else{
        unique_lock<mutex> ul(m);
        cv2.wait(ul); 
        if(!isOpen()) return false;
        t=myqueue.front();
        myqueue.pop();
        cv.notify_one();
    }
    return true;
}



bool put(T t){
    if(!isOpen())return false;
    if(myqueue.size()<N){
        {
        lock_guard<mutex> lg(m); 
        myqueue.push(t);
        cv2.notify_one(); 
        }
    }else{
        unique_lock<mutex> ul(m);
        cv.wait(ul);
        if(!isOpen())return false;
        myqueue.push(t);
        cv2.notify_one();
    }
    return true;
}

};

I solved this by changing from wait to wait_for in both get and put functions. For example in get:

if(!cv.wait_for(lock, std::chrono::milliseconds(2100), [this] { return !myQueue.empty();})) return false;

in this way threads wait just the set amount of time and calling myQueue.empty() doesn't require a proper lock (as suggested in the answers).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM