如何使用boost io_service.post()执行函数并使用数组或指针作为参数?

时间:2012-12-10 18:03:36

标签: c++ arrays multithreading boost boost-thread

在尝试构建一个可以使用boost 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时没有正确的内容,我认为这是因为它不在同一个线程内部调用。

那么,如何调整此构造以将我的数组作为参数传输?!

1 个答案:

答案 0 :(得分: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。但这是另一个故事。