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;
    
    };
  • 相关阅读:
    Struts2框架的学习遇到的问题1
    博客开通第100天
    RTK(Real Time Kinematic)实时动态差分定位技术
    HSRP 协议/ VRRP 协议(热备份路由协议)
    PKI 公钥基础设施
    路由器的工作原理
    VLAN基础知识
    Linux系统的 粘滞位、sgid和suid
    Kali Linux三步安装中文输入法(极简)
    ACL 包过滤技术
  • 原文地址:https://www.cnblogs.com/cnchengv/p/15725186.html
Copyright © 2011-2022 走看看