全是干货,纯代码!!!!!!!
#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::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);
}
CThread::~CThread()
{
if (m_bThreadRun)
{
m_bThreadRun = 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())
{
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);
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;
}
|