这是一个很常用的模式,以后用到了可以直接套用即可
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <condition_variable>
#include <atomic>
/**
* @brief 线程安全的生产者-消费者队列
*
* 这个类实现了一个简单的生产者-消费者模式,其中:
* - 生产者通过 process() 方法添加数据
* - 消费者在一个单独的线程中处理数据
* - 使用互斥锁和条件变量确保线程安全
* - 使用 std::atomic 避免数据竞争
*/
class ProducerConsumer
{
public:
ProducerConsumer()
{
m_thread = std::thread(&ProducerConsumer::workloop, this);
}
~ProducerConsumer()
{
m_isrunning = false;
m_cv.notify_all(); // 使用 notify_all() 确保唤醒所有等待的线程
if (m_thread.joinable())
{
m_thread.join();
}
}
void process(int ndata)
{
{
std::lock_guard<std::mutex> lc(m_mtx);
m_que.push(ndata);
}
m_cv.notify_one();
}
private:
void workloop()
{
try {
while (m_isrunning)
{
std::unique_lock<std::mutex> lc(m_mtx);
m_cv.wait(lc, [this]()
{ return !m_que.empty() || !m_isrunning; });
if (!m_isrunning && m_que.empty())
{
break;
}
if (!m_que.empty())
{
int ndata = m_que.front();
m_que.pop();
lc.unlock();
std::cout << "processing:" << ndata << std::endl;
}
}
} catch (const std::exception& e) {
std::cerr << "Worker thread exception: " << e.what() << std::endl;
} catch (...) {
std::cerr << "Worker thread unknown exception" << std::endl;
}
}
private:
std::thread m_thread;
std::mutex m_mtx;
std::queue<int> m_que;
std::condition_variable m_cv;
std::atomic<bool> m_isrunning{true};
};
int main()
{
{
ProducerConsumer pc;
pc.process(10);
pc.process(20);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
pc.process(30);
pc.process(40);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// 等待所有数据处理完成
std::cout << "All data submitted, waiting for processing..." << std::endl;
}
std::cout << "Program completed successfully!" << std::endl;
return 0;
}
运行结果:

1404

被折叠的 条评论
为什么被折叠?



