zl程序教程

您现在的位置是:首页 >  其他

当前栏目

sdbusplus:通过协程yield_method_call异步调用service的method

2023-04-18 16:46:54 时间

sdbusplus还提供了通过协程yield_method_call异步调用的方式:

//async_coroutine.cpp
#include <iostream>
#include <boost/asio.hpp>
#include <sdbusplus/bus.hpp>
#include <sdbusplus/asio/connection.hpp>
#include <sdbusplus/asio/object_server.hpp>

using namespace std;
using namespace sdbusplus;

void asyncCallCoroutines(shared_ptr<sdbusplus::asio::connection> conn, boost::asio::yield_context yield)
{
    boost::system::error_code ec;
    cout<<"1 yield_method_call AddInt begin"<<endl;
    int res1 = conn->yield_method_call<int>(yield, ec, 
        "calculate.service", "/calculate_obj", "calculate_infterface.data", "AddInt", 1, 2);
    if (ec)
    {
        cout<<"yield_method_call failed"<<endl;
    }
    else
    {
        cout<<"yield_method_call res="<<res1<<endl;
    }
    cout<<"2 yield_method_call AddInt end"<<endl;

    ec.clear();
    cout<<"3 yield_method_call AddInt begin"<<endl;
    int res2 = conn->yield_method_call<int>(yield, ec, 
        "calculate.service", "/calculate_obj", "calculate_infterface.data", "AddInt", 3, 4);
    if (ec)
    {
        cout<<"yield_method_call failed"<<endl;
    }
    else
    {
        cout<<"yield_method_call res="<<res2<<endl;
    }
    cout<<"4 yield_method_call AddInt end"<<endl;
}
 
int main()
{
    boost::asio::io_context io;
    auto conn = make_shared<sdbusplus::asio::connection>(io);

    cout<<"asyncCallCoroutines begin"<<endl;
    boost::asio::spawn(io, [conn](boost::asio::yield_context yield) {
        asyncCallCoroutines(conn, yield);
    });
    cout<<"asyncCallCoroutines end"<<endl;
    io.run();
    return 0;
}
编译程序,需要加入协程库:
g++ -o async_coroutine ./async_coroutine.cpp -lsdbusplus -lsystemd -lboost_coroutine
运行程序输出:
asyncCallCoroutines begin
asyncCallCoroutines end
1 yield_method_call AddInt begin
yield_method_call res=3
2 yield_method_call AddInt end
3 yield_method_call AddInt begin
yield_method_call res=7
4 yield_method_call AddInt end

通过输出:
asyncCallCoroutines begin
asyncCallCoroutines end
可以看出协程本身是被异步调用的

但是协程的内部是顺序调用的,有点类似是同步调用的:
1 yield_method_call AddInt begin
yield_method_call res=3
2 yield_method_call AddInt end
3 yield_method_call AddInt begin
yield_method_call res=7
4 yield_method_call AddInt end