大家都知道boost官方提供的聊天程序模型,由于工作需要我在上面的基础上增加图片发送的需求。发生崩溃原因。这个是发送消息的源码:
- void do_write(chat_message msg)
- {
- bool write_in_progress = !write_msgs_.empty(); //空的话变量为false
- write_msgs_.push_back(msg); //把要写的数据push至写队列
- if (!write_in_progress)//队列初始为空 push一个msg后就有一个元素了
- {
- boost::asio::async_write(socket_,
- boost::asio::buffer(write_msgs_.front().data(),
- write_msgs_.front().length()),
- boost::bind(&chat_client::handle_write, this,
- boost::asio::placeholders::error));
- }
- }
- void handle_write(const boost::system::error_code& error)//第一个消息单独处理,剩下的才更好操作
- {
- if (!error)
- {
- write_msgs_.pop_front();//刚才处理完一个数据 所以要pop一个
- if (!write_msgs_.empty())
- {
- boost::asio::async_write(socket_,
- boost::asio::buffer(write_msgs_.front().data(),
- write_msgs_.front().length()),
- boost::bind(&chat_client::handle_write, this,
- boost::asio::placeholders::error)); //循环处理剩余的消息
- }
- }
-
每次发送消息都是调用do_write函数,write_msgs_是保存消息的队列。表面上看是没有什么问题。但是当你连续调用这个函数的时候就会出现问题。因为频繁调用和各种对调函数。会出现write_msgs_.front()中write_msgs_队列为空崩溃。目前解决方法是加锁。确保pop_front()、push_back()函数不出现连续调用使front()函数调用崩溃问题。我不知道又没用更好的办法。希望大家能给我更好的意见,下面是我的源码:
{
boost::mutex::scoped_lock lock(mtx);
if (msg.data() !=NULL )
write_msgs_.push_back(msg); //把要写的数据push至写队列
if (!write_msgs_.empty())//队列初始为空 push一个msg后就有一个元素了
{
Message_Base Info = write_msgs_.front();
boost::asio::async_write(socket_,
boost::asio::buffer(Info.data(),
Info.length()),
boost::bind(&chat_client::handle_write, this,
boost::asio::placeholders::error));
}
}
void handle_write(const boost::system::error_code& error)//第一个消息单独处理,剩下的才更好操作
{
boost::mutex::scoped_lock lock(mtx);
if (!error)
{
if (!write_msgs_.empty())
write_msgs_.pop_front();//刚才处理完一个数据 所以要pop一个
if (!write_msgs_.empty())
{
Message_Base Info = write_msgs_.front();
boost::asio::async_write(socket_,
boost::asio::buffer(Info.data(),
Info.length()),
boost::bind(&chat_client::handle_write, this,
boost::asio::placeholders::error)); //循环处理剩余的消息
}
}
else
{
if (m_pCallBackTimeOut)
m_pCallBackTimeOut(RESULT_ERROR, (char*)error.message().c_str());
do_close();
}
}