使用异步boost asio代码进行同步操作

时间:2017-10-16 05:00:40

标签: c++ asynchronous boost-asio synchronous

我有一个用boost ASIO编写的服务器和客户端代码,它工作得很好。 由于同步和异步升级asio API是不同的,因此我可以以任何方式为异步通信编写的代码以同步方式而不是异步方式工作和工作。 ?

1 个答案:

答案 0 :(得分:2)

您可以在专用的io_service上运行任何异步代码,只需运行服务阻止:

Live On Coliru

#include <boost/asio.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <iostream>

using namespace std::chrono_literals;
using namespace boost::asio;
using boost::system::system_error;

io_service svc;
high_resolution_timer deadline(svc, 3s);

void task_foo() { 
    deadline.async_wait([](system_error) { std::cout << "task done\n"; });
}

int main() {
    task_foo();

    std::cout << "Before doing work\n";

    svc.run(); // blocks!

    std::cout << "After doing work\n";
}

打印

Before doing work
task done
After doing work

可替换地:

您可以随时使用等待阻止的期货:

<强> Live On Coliru

#include <boost/asio.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <boost/make_shared.hpp>
#include <future>
#include <iostream>
#include <thread>

using namespace std::chrono_literals;
using namespace boost::asio;
using boost::system::system_error;

io_service svc;
high_resolution_timer deadline(svc, 3s);

std::future<int> task_foo() {
    auto p   = boost::make_shared<std::promise<int> >();
    auto fut = p->get_future();

    deadline.async_wait([p](system_error) {
        std::cout << "task done\n";
        p->set_value(42);
    });

    return fut;
}

int main() {

    auto foo = task_foo();

    std::cout << "Before doing work\n";

    std::thread([] { svc.run(); }).detach(); // doesn't block!

    std::cout << "After starting work\n"; // happens before task completion

    auto result = foo.get(); // blocks again!

    std::cout << "Task result: " << result << "\n";
}

打印

Before doing work
After starting work
task done
Task result: 42

通过这种方式,您仍然可以同时运行io_service,即使特定任务完成同步foo.get()

,也不需要它完成