gpt4 book ai didi

c++ - asio::io_service::strand 的正确用法?

转载 作者:行者123 更新时间:2023-11-28 00:47:08 26 4
gpt4 key购买 nike

这是我的代码:

void client_connection::serve()
{
asio::async_read(this->socket_, asio::buffer(&buffer_, buffer_.size()),

// predicate/condition (do I wrap this?)
std::bind(&client_connection::handle_read_predicate, this->shared_from_this(), std::placeholders::_1, std::placeholders::_2),

// handler
this->strand_.wrap(std::bind(&client_connection::handle_read, this->shared_from_this(), std::placeholders::_1, std::placeholders::_2)));
}

std::size_t client_connection::handle_read_predicate(const asio::error_code& error, std::size_t bytes_)
{
// useless flawed function, for now

// std::cout << "test: reached predicate, " << bytes_ << std::endl;

return 0;
}

void client_connection::handle_read(const asio::error_code& error_, std::size_t bytes_)
{
// useless flawed function, for now

if (error_) return;

this->serve();
}

我的问题是,使用相同的 strand_ 对象来包装谓词/条件处理程序是否正确使用 asio::io_service::strand?如果是,为什么,如果不是,请解释。

最佳答案

没有必要将它包裹在链中。

根据 strand已记录,对于组合操作,例如 async_read 自由函数,所有中间处理程序都在处理程序的链中调用。这样做的副作用是 CompletionCondition 的所有中间调用也会从链中调用。

但是,确保在启动异步循环时在链中分派(dispatch) client_connection::serve() 的初始调用,作为初始 CompletionCondition 和异步读取套接字操作发生在调用者的上下文中。例如,在下图中,对 socket.async_read()client_connection::handle_read_predicate()client_connection::handle_read() 的所有调用code> 将出现在 strand 中:

void client_connection::start()
{
strand_.dispatch(std::bind(&client_connection::serve,
shared_from_this())) --------.
} |
.-----------------------------------------------------'
| .--------------------------------------------------.
V V |
void client_connection::serve() |
{ |
async_read(socket_, buffer, |
std::bind(&client_connection::handle_read_predicate, |
this), |
strand_.wrap( |
std::bind(&client_connection::handle_read, |
shared_from_this())); --. |
} | |
.-----------------------------------' |
V |
void client_connection::handle_read(...) |
{ |
if (error) return; |
serve(); ----------------------------------------------'
}

关于c++ - asio::io_service::strand 的正确用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15875359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com