The code below was an answer in this post as a socket-based event loop class. Socket based event loop
I wonder if anyone can generate an example of a client that uses this class.
"In your receiver thread on the client, you should use a thread-safe object to push and pop messages. If you have access to a C++11 compiler, You might consider std::vectorstd::shared_ptr<Messsage>. Here's a simple implementation of a thread-safe object that might suit your needs."
class MessageQueue
{
public:
typedef std::shared_ptr<Message> SpMessage;
bool empty() const {
std::lock_guard<std::mutex> lock(mutex_);
return messages_.empty();
}
SpMessage pop() {
std::lock_guard<std::mutex> lock(mutex_);
SpMessage msg(messages_.front());
messages_.pop_front();
return msg;
}
void push(SpMessage const& msg)
std::lock_guard<std::mutex> lock(mutex_);
messages_.push_back(msg);
}
private:
MessageQueue(const MessageQueue&); // disable
MessageQueue& operator=(const MessageQueue&); // disable
std::vector<SpMessage> messages_;
std::mutex mutex_;
};
typedef std::shared_ptr<MessageQueue> SpMessageQueue;
Aucun commentaire:
Enregistrer un commentaire