使用条件变量和unique_lock机制来创建线程安全的fifo队列

时间:2016-02-14 16:13:29

标签: c++ multithreading c++11 thread-safety fifo

考虑这个FIFO队列(using namespace std),这是我在阅读c ++ 11更新功能后创建的。

void Fifoqueue::pop(int& item)
{
    unique_lock<mutex> lock(mtx);
    cv.wait(lock , [this]()//unlock mutex and wait here for notify_* sig
    { 
        return !q.empty(); //block until both notify_* sig is caught and the queue is not empty. 
    });//when we reach here the mutex is locked and execution continues

    item = q.front();
    q.pop();    
}

bool Fifoqueue::pop_try(int& item)
{   
    bool bHasNewData = false;
    unique_lock<mutex> ulock(mtx,defer_lock);//defer lock,so noblock        
    if ( ulock.try_lock() && !q.empty() )//q.empty() will only be checked on a successful locking
    {
        bHasNewData = true;
        item = q.front();
        q.pop();        
    }

    return bHasNewData;
}

void Fifoqueue::push(const int& item)
{
    lock_guard<mutex> lock(mtx);
    q.push( item );
    cv.notify_one();
}

其中

queue< int , list<int> > q;
condition_variable cv;
mutex mtx;

您是否可以验证我是否已正确理解unique_lockconditional_variables(根据我的在线评论),以便创建阻止和非阻止pop调用这个队列?线程安全是否有保障?

0 个答案:

没有答案