首页 > 编程 > C++ > 正文

c++自定义队列

2019-11-08 01:06:09
字体:
来源:转载
供稿:网友
#ifndef BLOCKINGQUEUE_H_#define BLOCKINGQUEUE_H_#include <list>#include <vector>#include <queue>#include <utils/Mutex.h>#include <semaphore.h>#include <utils/Condition.h>#define DISALLOW_COPY_AND_ASSIGN(TypeName) /    TypeName(const TypeName&);                /    TypeName& Operator=(const TypeName&)namespace android {template<typename T, int count>class BlockingQueue {PRivate:    mutable std::list<T> mList;    mutable Mutex mLock;    mutable Condition mContentAvailableCondition;//volatile int m_size;    T front(bool remove) {        Mutex::Autolock autolock(mLock);        while ( mList.empty() ) {int ret =0;           ret = mContentAvailableCondition.waitRelative(mLock, 200000000);  //m_size = mList.size(); // ALOGD("wujw %s %d %lld %d %d %d %d /n", __FUNCTION__, __LINE__, m_size, &m_size, ret, mList.empty(), gettid());        }        T e = *(mList.begin());        if (remove) {            mList.erase(mList.begin());        }        return e;    }    DISALLOW_COPY_AND_ASSIGN(BlockingQueue);public:    BlockingQueue() {    }    ~BlockingQueue() {    }    bool empty() {        Mutex::Autolock autolock(mLock);        return mList.empty();    }    int size() {        Mutex::Autolock autolock(mLock);        return mList.size();    }    void clear() {        Mutex::Autolock autolock(mLock);        mList.clear();    }    T peek() {        return front(false);    }    T pop() {//ALOGD("wujw %s %d /n", __FUNCTION__, __LINE__);        return front(true);    }    void push(T e) {        Mutex::Autolock autolock(mLock);if(mList.size( ) <= count){        mList.push_back(e);//ALOGD("wujw %s %d %d /n", __FUNCTION__, __LINE__,mList.size( ));}//m_size = mList.size( );//ALOGD("wujw %s %d %d %lld %d /n", __FUNCTION__, __LINE__,m_size,&m_size,gettid());        mContentAvailableCondition.signal();    }};

} /* namespace android */

#endif

typedef struct{

char buf[100];

int nLen;

}TestData;

class Test{

BlockingQueue<TestData, 20>  testQueue;

};

readDataThread()

{

TestData testdata;

ret = read(fd,testdata.buf,len);

testdata.nLen = ret;

pThis->testQueue.push(testdata);

}

sendDataThread()

{

TestData testdata;

pThis->testQueue.pop(testdata);

ret = write(fd,testdata.buf,testdata.nLen);

}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选