一个接收数据的缓存参考

 

因为考虑多线程处理,所以加了互斥;对缓存最大值没加限制。

typedef struct {
    int event;
    int type;
    MSG_INFO info;
} ADPT_CLIENT_DATA;


class BCallback {
    public:
        int32_t Callback(const int32_t &evt, const int32_t &type, const MSG_INFO &info) {
            ADPT_CLIENT_DATA data = {};

            data.event = evt;
            data.type  = type;
            data.info  = info;

            (void)pthread_mutex_lock(&m_mInfoMutex);
            m_lInfoVehicle.push_back(data);
            (void)pthread_cond_signal(&m_cEmptyCond);
            (void)pthread_mutex_unlock(&m_mInfoMutex);

            return 0;
        };

        void GetInfo(int32_t &event, int32_t &type, MSG_INFO &info) {
            (void)pthread_mutex_lock(&m_mInfoMutex);
            while (m_lInfoVehicle.empty()) {
                (void)pthread_cond_wait(&m_cEmptyCond, &m_mInfoMutex);
            }

            event= m_lInfoVehicle.front().event;
            type = m_lInfoVehicle.front().type;
            info = m_lInfoVehicle.front().info;
            m_lInfoVehicle.pop_front();
            (void)pthread_mutex_unlock(&m_mInfoMutex);

        };

        BCallback() {
            /* init data */
            if (pthread_mutex_init(&m_mInfoMutex, NULL) < 0) {
                //printf("init mutex error\n"); 
            }

            if (pthread_cond_init(&m_cEmptyCond, NULL) < 0) {
                //printf("init condition error\n");
                //return -1;
            }

            m_lInfoVehicle.clear();
        };

        ~BCallback() {
            m_lInfoVehicle.clear();

            (void)pthread_mutex_destroy(&m_mInfoMutex);
            (void)pthread_cond_destroy(&m_cEmptyCond);
        };

    private:
        pthread_mutex_t m_mInfoMutex;
        pthread_cond_t m_cEmptyCond;
        std::list<ADPT_CLIENT_DATA> m_lInfoVehicle;
};

 

posted @ 2022-10-21 15:25  sciapex  阅读(21)  评论(0编辑  收藏  举报