C++11 RXCPP:阻塞函数超时
考虑一个阻塞函数:this_thread::sleep_for(毫秒(3000)) 我试图获得以下行为:C++11 RXCPP:阻塞函数超时,c++11,rxcpp,C++11,Rxcpp,考虑一个阻塞函数:this_thread::sleep_for(毫秒(3000)) 我试图获得以下行为: Trigger Blocking Function |---------------------------------------------X 我想触发阻塞函数,如果它花费的时间太长(超过两秒),它应该超时 我已经做了以下工作: my_connection = observable<>::create<int>([](subscr
Trigger Blocking Function
|---------------------------------------------X
我想触发阻塞函数,如果它花费的时间太长(超过两秒),它应该超时
我已经做了以下工作:
my_connection = observable<>::create<int>([](subscriber<int> s) {
auto s2 = observable<>::just(1, observe_on_new_thread()) |
subscribe<int>([&](auto x) {
this_thread::sleep_for(milliseconds(3000));
s.on_next(1);
});
}) |
timeout(seconds(2), observe_on_new_thread());
好问题!上述情况非常接近 下面是一个如何使阻塞操作适应rxcpp的示例。它不需要发出http请求 以下内容应符合您的预期
auto sharedThreads = observe_on_event_loop();
auto my_connection = observable<>::create<int>([](subscriber<int> s) {
this_thread::sleep_for(milliseconds(3000));
s.on_next(1);
s.on_completed();
}) |
subscribe_on(observe_on_new_thread()) |
//start_with(0) | // workaround bug in timeout
timeout(seconds(2), sharedThreads);
//skip(1); // workaround bug in timeout
my_connection.as_blocking().subscribe(
[](int){},
[](exception_ptr ep){cout << "timed out" << endl;}
);
auto-sharedThreads=observe_on_event_loop();
自动my_连接=可观察::创建([](订户){
此线程::睡眠时间(毫秒(3000));
s、 下一步(1);
s、 在_completed()上;
}) |
订阅(在新线程()上观察)|
//以(0)开始|//解决超时错误
超时(秒(2),共享线程);
//跳过(1);//解决超时错误的方法
my_connection.as_blocking().订阅(
[](int){},
[](异常){cout Hi Kirk,谢谢你的输入。我运行了你建议的代码段。似乎在on\u错误之前触发了on\u next
。我怀疑是这个线程::sleep\u for()
正在阻止启动内部计时器的超时。如果删除s.on_completed
,将触发on_next
,然后从超时中触发on_error
。这就是我没有首先尝试的原因。我在timeout操作符中发现了一个错误,我已使用该错误的解决方法更新了答案。我合并了一个PR这修复了timeout
。不再需要此解决方案!保留此解决方案将有一些较小的开销,但在其他情况下,此解决方案仍将与修复的timeout
相同。我认为另一种方法是:auto connection=timeout.amb(blocking\u function\u observeable)
auto sharedThreads = observe_on_event_loop();
auto my_connection = observable<>::create<int>([](subscriber<int> s) {
this_thread::sleep_for(milliseconds(3000));
s.on_next(1);
s.on_completed();
}) |
subscribe_on(observe_on_new_thread()) |
//start_with(0) | // workaround bug in timeout
timeout(seconds(2), sharedThreads);
//skip(1); // workaround bug in timeout
my_connection.as_blocking().subscribe(
[](int){},
[](exception_ptr ep){cout << "timed out" << endl;}
);