协程局部变量在boost
Coroutine-local variable in boost
我正在寻找类似于线程局部变量的东西,但对于boost:: cor棕(实际上我使用boost:asio::spawn)。考虑以下代码:
void coroutine_work(boost::asio::yield_context yield) {
async_foo( yield );
some_function();
}
void some_function() {
fprintf(log_fd, "%s Some function called", the_magic_request_id);
}
我想把这个the_magic_request_id
设置为初始化请求时的某个值,它将像"当前请求id"一样服务。
如果没有这个,我必须将the_magic_request_id
传递给每个功能和每个模块,这些功能和模块在项目中进行登录。some_function
只是一个例子,实际上我有很多类,他们做不同的工作,但他们都需要yield_context
和the_magic_request_id
来创建一个实例。我想简化这些类的接口。
可能是有可能设置"on_sleep"answers"on_resume"挂钩,这将设置一个全局变量?或者boost::coroutine已经为此提供了一些面向用户的机制?
不使用boost。协程(boost::asio::yield_context)你可以使用boost。光纤(user-land threads,boost::fibers::asio::yield_context)。提振。光纤支持fiber_specific_ptr (equals . to boost)。线程的thread_specific_ptr)。
文档:http://olk.github.io/libs/fiber/doc/html/index.html
可以使用绑定函数对象来包含状态。
事实上,绑定函数对象可以优雅地表示为带有捕获的lambda。确保捕获是按值的(这样你就不会意外地与其他实例共享状态),如果不是,它们所引用的对象就足够长寿。
。
extern std::ostream& log_stream; // for exposition only
struct coroutine_work {
boost::uuids::uuid the_magic_request_id = boost::uuids::random_generator{}();
void operator()(boost::asio::yield_context yield) {
async_foo(yield);
some_function();
}
void some_function() const {
log_stream << the_magic_request_id << " Some function calledn";
}
}
另外:
static void some_function(boost::uuids::uuid const& reqid) const {
log_stream << reqid << " Some function calledn";
}
struct coroutine_work {
boost::uuids::uuid the_magic_request_id = boost::uuids::random_generator{}();
void operator()(boost::asio::yield_context yield) {
async_foo(yield);
some_function(the_magic_request_id);
}
}
或者转换成lambda形式:
static void some_function(boost::uuids::uuid const& reqid) const {
log_stream << reqid << " Some function calledn";
}
// somewhere else:
{
boost::uuids::uuid the_magic_request_id = boost::uuids::random_generator{}();
auto coroutine_work = [the_magic_request_id](boost::asio::yield_context yield) {
async_foo(yield);
some_function(the_magic_request_id);
}
}
- 使用的未初始化局部变量'Quick'
- 修复未初始化的局部变量错误
- 局部变量保留函数中的值
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- Gnuplot_i.hpp C++接口绘制局部变量而不是文件
- 如何在函数外部访问函数中局部变量的值?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- C++中静态方法的局部变量范围
- 未初始化的局部变量错误甚至认为我初始化了它(C++)
- 离开范围后如何保护局部变量的值?
- 局部变量名称冲突
- C++ lambda:如何'freeze'局部变量的值?
- 我应该使我的局部变量常量还是可移动的
- 使用 BOOST ASIO 在异步服务器中发送局部变量
- boost::optional<>如何处理局部变量?
- 在Boost Phoenix中获取局部变量的类型
- 协程局部变量在boost
- 我可以创建一个局部变量的boost::shared_ptr吗
- Boost线程-使用局部变量作为参数