用C++写一个单例类,这个类有一个消息队列,存和取消息队列中的数据都需要用锁。
时间: 2024-05-10 11:16:11 浏览: 47
以下是一个简单的单例类示例,其中包含一个消息队列和用于保护队列的锁:
```c++
class MessageQueue {
public:
static MessageQueue& getInstance() {
static MessageQueue instance;
return instance;
}
void addMessage(const std::string& message) {
std::lock_guard<std::mutex> lock(m_mutex);
m_queue.push(message);
}
std::string getMessage() {
std::lock_guard<std::mutex> lock(m_mutex);
if (m_queue.empty()) {
return "";
}
std::string message = m_queue.front();
m_queue.pop();
return message;
}
private:
MessageQueue() {}
std::queue<std::string> m_queue;
std::mutex m_mutex;
};
```
在上面的示例中,`getInstance()` 方法返回一个 `MessageQueue` 的单例实例。`addMessage()` 方法向队列中添加消息,`getMessage()` 方法从队列中获取消息。
在这个类中,我们使用了 `std::mutex` 来保护队列,确保在修改队列时只有一个线程可以访问它。在 `addMessage()` 和 `getMessage()` 方法中,我们使用了 `std::lock_guard`,它会在离开块时自动释放锁,从而避免了死锁的可能性。
请注意,这个示例类并不是线程安全的,因为多个线程可能同时调用 `addMessage()` 和 `getMessage()` 方法,从而导致竞争条件。要使其线程安全,您需要在调用 `getInstance()` 方法时使用互斥锁,或者使用双重检查锁定模式(DCLP)。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)