• twobuffer


    #pragma once
    #include <stdio.h>
    #include <iostream>
    #include <string>
    #include <thread>
    #include <mutex>
    
    class CTwoBuffer
    {
    public:
        CTwoBuffer()
            :buffer1(nullptr)
            , buffer2(nullptr)
            , bufferRead(nullptr)
            , bufferWrite(nullptr)
            , bufferSize(0)
            , bufferReadIndex(0)
            , bufferWriteIndex(0)
            , bytesCanRead(0)
        {
    
        };
        void Init(int buffSize = 1024 * 1024)
        {
            printf("block init--%d-->", buffSize);
            buffer1 = new unsigned char[buffSize];
            buffer2 = new unsigned char[buffSize];
            bufferRead = buffer1;
            bufferWrite= buffer2;
    
            if (!buffer1||!buffer2) return;
            this->bufferSize = buffSize;
        }
    
        void Write(unsigned char* src, int size)
        {
          //  printf("want write %d ,%d %d, bsize %d \n", size, readIndex, writeIndex, bufferSize);
            if (!src || size == 0) return;
            std::lock_guard<std::mutex> lk(lock);
            if (size >= bufferSize - bufferWriteIndex) {
                std::this_thread::sleep_for(std::chrono::microseconds(50));
                printf("buffer now is full  %d,%d,%d!", size, bufferSize, bytesCanRead);
    
                //遗弃和交换
    
                return;
            }
            memcpy(bufferWrite + bufferWriteIndex, src, size);
            bufferWriteIndex += size;
    
        }
    
        int Read(uint8_t* dst, int size)
        {
            std::this_thread::sleep_for(std::chrono::microseconds(80));
            //read小于则等待
            //就看这两个的--
            //printf("want Read %d ,%d %d \n", size, readIndex, writeIndex);
            if (!dst || size == 0) return 0;
            std::lock_guard<std::mutex> lk(lock);
            //必须50k缓冲
            if (size > bufferSize - bufferReadIndex) {
                std::this_thread::sleep_for(std::chrono::microseconds(50));
                printf("Buffer is empty!---->");
    
                //翻转等
                return 0;
            }
    
            memcpy(dst, bufferRead, size);
            bufferReadIndex += size;
            return size;
        }
    
    
        private:
            unsigned char* buffer1;
            unsigned char* buffer2;
            unsigned char* bufferRead;
            unsigned char* bufferWrite;
            int bufferSize;
            int bufferReadIndex;
            int bufferWriteIndex;
            int bytesCanRead;
            std::mutex lock;
    
    };
  • 相关阅读:
    Kaggle 神器 xgboost
    改善代码可测性的若干技巧
    IDEA 代码生成插件 CodeMaker
    Elasticsearch 使用中文分词
    Java性能调优的11个实用技巧
    Lucene 快速入门
    Java中一个字符用unicode编码为什么不是两字节
    lucene 的评分机制
    面向对象设计的 10 条戒律
    2019.10.23-最长全1串(双指针)
  • 原文地址:https://www.cnblogs.com/cnchengv/p/15725186.html
Copyright © 2020-2023  润新知