【发布时间】:2021-11-29 16:01:29
【问题描述】:
我需要调用远程服务器请求的方法。之后我想等待答案,并且等待不会被其他异步函数/对象(例如计时器)阻塞。
方法 got_response(...) 告诉用户他从远程服务器得到了答案,方法也得到了我们作为答案得到的条目数据。下面我得到了我的解决方案,但是有时可以在单线程中调用计时器,这将导致方法 got_response() 挂起。
如何在其他线程中调用计时器以保证答案模拟。我的问题还有其他解决方案吗?
#include <iostream>
#include <boost/asio.hpp>
#include <future>
#include <thread>
#include <vector>
using namespace std;
namespace io = boost::asio;
struct Reply
{
atomic<bool> ready;
atomic<int> result;
future<void> future_result;
Reply()
{
ready = false;
result = 0;
}
void call()
{
cout << "retry called!" << endl;
future_result = async([&]()
{
while (!ready)
{
this_thread::yield();
}
});
}
int get()
{
future_result.wait();
return result.load();
}
void got_response(int res)
{
result = res;
ready = true;
}
};
int main()
{
Reply reply;
reply.call();
io::io_context context(4);
io::steady_timer timer1(context, std::chrono::seconds(2));
timer1.async_wait([&](const boost::system::error_code &ec)
{ cout << "timer 1, thread name: " << this_thread::get_id() << endl; });
io::steady_timer timer2(context, std::chrono::seconds(3));
timer2.async_wait([&](const boost::system::error_code &ec)
{
cout << "timer 2, thread name: " << this_thread::get_id() << endl;
cout << reply.get() << endl;
});
io::steady_timer timer3(context, std::chrono::seconds(10));
timer3.async_wait([&](const boost::system::error_code &ec)
{
cout << "timer 3, thread name: " << this_thread::get_id() << endl;
reply.got_response(1337);
});
vector<thread> threads;
auto count = 2;
for (int n = 0; n < count; ++n)
{
threads.emplace_back([&]
{ context.run(); });
}
for (auto &th : threads)
{
th.join();
}
}
结果:
retry called!
timer 1, thread name: 140712511198784
timer 2, thread name: 140712519591488
timer 3, thread name: 140712511198784
1337
【问题讨论】:
标签: c++ multithreading boost asio stdasync