c++ - 如何使用 boost::asio io_service 异步运行函数
问题描述
我有异步 tcp 服务器,它从客户端读取异步消息。我应该对我推荐的按摩进行一些操作,然后将答案发送给客户。操作应该是异步的,并且在操作完成后,服务器应该向客户端发送应答。
我想做下一个:
//...
std::string answer;
boost::asio::io_service &io_service_;
void do_read(){
//async read from client and call on_read()
}
void on_read(std::string msg){
//here I have a problem - I don't know, how to call func() asynchronous
//I want to do something like this:
RunAcync(boost::bind(&CClientSession::func, shared_from_this(), msg)
, boost::bind(&CClientSession::on_func_executed, shared_from_this())
,io_service_ );
do_read();
}
void func(std::string msg) {
//do long work hare with msg
answer = msg;
}
void on_func_executed(){
do_write(answer);
}
void do_write(std::string msg){
//async write to client and call on_write()
}
void on_write(){
do_read();
}
//...
所以我的函数应该在与 io_service 相同的线程下执行。
PS:: 这是类的一部分,适用于客户端
解决方案
您可以在某处运行一个函数(可能作为post()
相同的 -ed 任务io_service
)。然后,完成后,只需开始下一个异步操作:
void on_read(std::string msg){
auto self = shared_from_this();
io_service_.post(
boost::bind(&CClientSession::func, self, msg, boost::bind(&CClientSession::on_func_executed, self)));
do_read();
}
void func(std::string msg, std::function<void()> on_complete) {
//do long work hare with msg
answer = msg;
on_complete();
}
但是,在这种情况下,从内部链接可能更简单func
:
void on_read(std::string msg){
io_service_.post(
boost::bind(&CClientSession::func, shared_from_this(), msg));
do_read();
}
void func(std::string msg) {
//do long work hare with msg
answer = msg;
do_write(answer);
}
推荐阅读
- django - ALLOWED_HOSTS 在部署到 Elastic Beanstalk 的 Django 应用程序中不起作用
- matlab - 区间绘图函数
- c# - Referencing other web project overriding current authentication ASP.NET mvc
- powershell - 为什么在使用 windows 窗体时使用带有变量的命令开关返回空变量?
- r - 在geom_point中使用cut时如何在ggplot中添加椭圆
- html - 当最后一个路由字符不带/带'/'时,Express 服务器分别加载带/不带 css/js 的 html 页面
- laravel - Vue:如何刷新新数据?
- java - 使用 gradle 构建 android 应用时的问题
- java - 如何测试 RestTemplate 的线程安全性?
- java - 使用服务时更新 ProgressBar 的进度?