#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;
};