如何使用boostsio_service.post()执行函数并使用数组或指针作为参数
How can I execute a function with boosts io_service.post() and use an array or pointer as parameter?
当我试图构建一个程序时,它可以用boostsasync_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));
}
它确实编译了,但当调用write_buf
时,pMsg
没有正确的内容,我认为这是因为它不是在同一个线程内调用的。
那么,我如何调整这个构造以将数组作为参数进行传递呢?!
你似乎很清楚你的问题在哪里。快速解决方法是通过复制其内容来传递缓冲区:
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。但那是另一回事。
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”