zoukankan      html  css  js  c++  java
  • 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;
    
    };
  • 相关阅读:
    P1726 上白泽慧音
    P1993 小k的农场
    P1983 车站分级
    P1525 关押罪犯【二分+二分图】
    P1268 树的重量【构造】
    P1113 杂务
    F.Three pahs on a tree
    P1522 牛的旅行
    两个约束下的dp问题
    dp 最大正方形
  • 原文地址:https://www.cnblogs.com/cnchengv/p/15725186.html
Copyright © 2011-2022 走看看