1. 程式人生 > >C++ STL容器執行緒安全的模版類

C++ STL容器執行緒安全的模版類

STL的容器都是非執行緒安全的,模仿JDK,寫了一個通用的執行緒安全的模版類

template<typename T, typename D = deque<T> >

class TC_ThreadQueue : protected TC_ThreadLock
{
public:


    typedef D queue_type;


    /**
     * 從頭部獲取資料, 沒有資料則等待
     *
     * @param t
     * @param millsecond : 阻塞等待時間(ms)
     * @return bool: true, 獲取了資料, false, 無資料
     */
    bool pop_front(T& t, size_t millsecond = 0)
    {
        Lock lock(*this);   //方法同步塊


        if (_queue.empty())
        {
            if(millsecond == 0)
            {
                return false;
            }
            timedWait(millsecond);    //等待時間
        }


        if (_queue.empty())    //如果到時間了仍然是空的,則返回false
        {
            return false;
        }


        t = _queue.front();     
        _queue.pop_front();   //彈出並且刪除


        return true;
    }


    /**
     * 通知等待在佇列上面的執行緒都醒過來
     */
    void notifyT()
    {
        Lock lock(*this);
        notifyAll();     
    }


    /**
     * 放資料到佇列
     * @param t
     */
    void push_back(const T& t)
    {
        Lock lock(*this);


        //如果接收佇列是空的, 由於該呼叫後, 將有資料, 因此通知其他執行緒
        if(_queue.empty())
        {
            notifyAll();       //根據滯後通知的語義,在push_back的方法末尾正式解除wait的阻塞
        }


        _queue.push_back(t);    

//解除所有wait阻塞操作

    }


    /**
     * 等到有資料才交換
     * @param q
     * @millsecond : 阻塞等待時間(ms), 0:表示不阻塞
     * @return true:有資料, false:無資料
     */
    bool swap(queue_type &q, size_t millsecond = 0)
    {
        Lock lock(*this);


        if (_queue.empty())
        {
            if(millsecond == 0)
            {
                return false;
            }
            timedWait(millsecond);
        }


        if (_queue.empty())
        {
            return false;
        }


        q.swap(_queue);


        return true;
    }


    /**
     * 佇列大小
     *
     * @return size_t
     */
    size_t size() const
    {
        Lock lock(*this);
        return _queue.size();
    }


    /**
     * 清空佇列
     */
    void clear()
    {
        Lock lock(*this);
        _queue.clear();
    }


    /**
     * 是否資料為空
     *
     * @return bool
     */
    bool empty() const
    {
        Lock lock(*this);
        return _queue.empty();
    }


protected:
    /**
     * 佇列
     */
    queue_type         _queue;


};