0

在尝试构建一个可以使用 boosts 传输数据块/数组的程序时,async_write我的线程可能遇到了问题:

这就是我想要执行的:

write(unsigned char *pMsg, unsigned short nMsgLen){
      io_service_.post(boost::bind(&m_client::write_buf, this, pMsg, nMsgLen));
}

write_buf(unsigned char *pMsg, unsigned short nMsgLen){

          boost::asio::async_write(target,
                            boost::asio::buffer(pMsg, nMsgLen),
                            boost::bind(&m_client::write_buf_compl,
                            this,
                            boost::asio::placeholders::error));
}

它确实编译,但pMsg没有正确的内容,何时write_buf被调用,我认为这是因为它不是在同一个线程内调用的。

那么,我该如何调整这个结构来将我的数组作为参数传输呢?!

4

1 回答 1

0

看起来你很清楚你的问题出在哪里。它的快速解决方法是通过复制其内容来传递该缓冲区:

void write(unsigned char *pMsg, unsigned short nMsgLen) {
    // TODO: Take care of exception safety...
    char *pMsgCopy = (char *)malloc(nMsgLen);
    memcpy(pMsgCopy, pMsg, nMsgLen);
    io_service_.post(boost::bind(&m_client::write_buf, this,
                                 pMsgCopy, nMsgLen));
}

void write_buf(unsigned char *pMsg, unsigned short nMsgLen)
{
    // Achtung! Don't forget to free memory in complection callback.
    boost::asio::async_write(target,
                             boost::asio::buffer(pMsg, nMsgLen),
                             boost::bind(&m_client::write_buf_compl,
                                         this,
                                         boost::asio::placeholders::error));
}

void write_buf_compl(...)
{
    free(pMsg);
}

如果您对效率很着迷,那么您可以通过让调用者write()首先提供动态分配的缓冲区来避免复制。但是,如果您实际上对性能很着迷,那么我建议您不要使用 Boost.ASIO。不过那是另一回事了。

于 2012-12-10T18:14:05.600 回答