#include <queue>
#include <string>
#include <mutex>
#include <thread>
#include <iostream>
class CBuffer
{
public:
CBuffer() {}
~CBuffer() {}
static CBuffer* GetBuffer()
{
if (!m_buffer){
m_buffer = new CBuffer();
}
return m_buffer;
}
int GetSize()
{
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue_list.size();
}
bool IsEmpty()
{
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue_list.empty();
}
bool IsFull()
{
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue_list.size() == BUFFER_SIZE;
}
bool Push(const std::string& str)
{
if (!IsFull()) {
std::lock_guard<std::mutex> locker(m_mutex);
m_queue_list.push(str);
return true;
}
return false;
}
bool Pop(std::string& str)
{
if (!IsEmpty()) {
std::lock_guard<std::mutex> locker(m_mutex);
str = m_queue_list.front();
m_queue_list.pop();
return true;
}
return false;
}
private:
std::mutex m_mutex;
std::queue<std::string> m_queue_list;
static CBuffer* m_buffer;
static int BUFFER_SIZE;
};
CBuffer* CBuffer::m_buffer = nullptr;
int CBuffer::BUFFER_SIZE = 100;
std::shared_ptr<CBuffer> gBuffer(CBuffer::GetBuffer());
class Producer
{
public:
bool Produce(const std::string& s)
{
return gBuffer->Push(s);
}
};
class Consumer
{
public:
bool Consume(std::string& s)
{
return gBuffer->Pop(s);
}
};
bool bThreadStart = true;
void thread1()
{
Producer producer;
while (bThreadStart)
{
std::string s = std::to_string( rand() % 100 + 1);
if (producer.Produce(s)) {
std::cout << "produce s:" << s << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void thread2()
{
Consumer consumer;
while (bThreadStart)
{
std::string s;
if (consumer.Consume(s)) {
std::cout << "consume s:" << s << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
srand(time(nullptr));
std::thread t1(thread1);
std::thread t2(thread2);
t1.join();
t2.join();
return 0;
}