🌷🌷🌷🌷① 使用std::mutex实现线程安全的队列
🌷🌷🌷🌷② 使用std::condition_variable实现线程间通信
🌷🌷🌷🌷③ 使用std::shared_mutex实现读写锁
🌷🌷🌷🌷④ 使用std::atomic实现原子操作
① 使用std::mutex实现线程安全的队列
在这个例子中,我们将介绍如何使用std::mutex实现线程安全的队列。在多线程编程中,队列是一种非常常见的数据结构,用于存储和管理数据。但是,在多线程环境中,如果不加以保护,多个线程同时对队列进行push和pop的操作可能会导致数据竞争的问题。为了解决这个问题,我们可以使用std::mutex来保护队列的访问。具体实现方法是,在push和pop操作前,分别使用std::lock_guardstd::mutex来锁定mutex,从而避免多线程之间的数据竞争。代码实现如下:
template<typename T>
class ThreadSafeQueue {
public:
ThreadSafeQueue() {}
void push(T value) {
std::lock_guard<std::mutex> lock(m_mutex);
m_queue.push(value);
}
bool try_pop(T& value) {
std::lock_guard<std::mutex> lock(m_mutex);
if (m_queue.empty()) {
return false;
}
value = m_queue.front();
m_queue.pop();
return true;
}
bool empty() const {
std::lock_guard<std::mutex> lock(m_mutex);
return m_queue.empty();
}
private:
std::queue<T> m_queue;
mutable std::mutex m_mutex;
};
在这个例子中,我们使用了std::lock_guardstd::mutex来锁定mutex,保护了队列的访问。同时,我们还使用了mutable关键字来修饰m_mutex,表示在const成员函数中也可以对它进行修改。