全是干货,纯代码!!!!!!!
#include <iostream>
#include <list>
#include <thread>
#include <atomic>
#include <condition_variable>
class CThread
{
public:
CThread();
~CThread();
/* 生产者 */
void ProductFunc(const std::string &szMsg); // 生成函数
private:
/* 消费者 */
void ConsunmerThreadFunc(); // 消费线程函数
std::string PopList(); // 取出队列信息函数
private:
std::mutex m_Mutex; // 线程锁
std::atomic_bool m_bThreadRun = false; // 原子布尔型 std::atomic_bool 等价于 sta::atomic<bool>
std::condition_variable m_ThreadSemaphore; // 线程唤醒条件变量
std::thread m_WorkThread; // 工作线程对象
std::list<std::string> m_CacheList; // 缓存队列
};
CThread::CThread()
{
// 构造函数中开启线程,初始化对象时即开启线程
m_bThreadRun = true; // 工作状态置为开启
m_WorkThread = std::thread(&CThread::ConsunmerThreadFunc, this); // std::thread开启线程
}
CThread::~CThread()
{
// 析构函数中停止线程
if (m_bThreadRun) // 先判断状态
{
m_bThreadRun = false; // 状态置为false
m_ThreadSemaphore.notify_all(); // 唤醒线程
if (m_WorkThread.joinable()) // 等待线程退出的经典操作
{
m_WorkThread.join();
}
}
}
void CThread::ProductFunc(const std::string &szMsg)
{
std::lock_guard<std::mutex> lockGuard(m_Mutex); // 上锁
m_CacheList.push_back(std::move(szMsg)); // 右值插入数据
if (m_CacheList.size() > 1000) // 数据上限控制
{
m_CacheList.pop_front(); // 丢弃之前的数据
}
m_ThreadSemaphore.notify_one(); // 唤醒工作线程
}
void CThread::ConsunmerThreadFunc()
{
while (m_bThreadRun)
{
std::string szMsg = std::move(PopList()); // 从队列中取出信息
if (szMsg.empty())
{
// 没有消息,则休眠2s等待新消息
std::unique_lock<std::mutex> uniqueLock(m_Mutex);
m_ThreadSemaphore.wait_for(uniqueLock, std::chrono::seconds(2));
continue;
}
std::cout << "new message: " << szMsg.c_str() << std::endl;
}
}
std::string CThread::PopList()
{
std::string szMsg;
std::unique_lock<std::mutex> uniqueLock(m_Mutex); // 上锁 注:此处可用 std::lock_guard<std::mutex> 自动解锁
if (!m_CacheList.empty())
{
szMsg = std::move(m_CacheList.front()); // 右值取出数据
m_CacheList.pop_front(); // 队列中删除取出的数据
}
uniqueLock.unlock(); // 解锁
return szMsg;
}
int main(int argc, char *argv[])
{
CThread myThread;
while (true)
{
myThread.ProductFunc("hello! every one."); // 产生一条数据
std::this_thread::sleep_for(std::chrono::seconds(1)); // 等待一秒
}
return 0;
}