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

标签 c++ asynchronous boost-asio synchronous

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

最佳答案

您可以在专用的 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

或者:

您始终可以使用可以等待阻塞的 future :

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())

关于c++ - 使用异步boost asio代码进行同步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46763232/

相关文章:

python - 用于允许断开连接的仅发送协议(protocol)的扭曲客户端

c++ - c++中的异步处理

c++ - 如何创建 boost ssl iostream?

c++ - 如何从多个线程安全地写入套接字?

c++ - 使用指针对单链表进行排序

c++ - 命名管道相对于匿名管道的优势c++

c++ - 如何将 const 指针的 vector const_cast 转换为非常量指针的 vector ?

c++ - 如何在 XML 文本(标签内)中搜索换行符?

node.js - Node/Gulp同步删除任务内的目录

c++ - 使用 libevent 或 boost::asio 在单线程中建立多个 tcp 连接。这是可能的?