zl程序教程

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

当前栏目

sdbusplus:通过async_send异步调用service的method

2023-04-18 16:49:12 时间

下面的例子通过async_send完成异步调用:

//async_send.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 asyncCallSend(shared_ptr<sdbusplus::asio::connection> conn)
{
    
    auto mesg1 = conn->new_method_call("calculate.service", "/calculate_obj", "calculate_infterface.data", "AddInt");
    mesg1.append(1, 2);

    cout<<"1 async_send begin"<<endl;
    conn->async_send(mesg1, [](boost::system::error_code ec, message::message& ret) {
        cout << "async_send callback
";
        if (ec)
        {
            cout<<"error with async_send"<<endl;
            return;
        }
        int data = 0;
        ret.read(data);
        cout<<"ret data="<<data<<endl;
    });
    cout<<"2 async_send end"<<endl;

    auto mesg2 = conn->new_method_call("calculate.service", "/calculate_obj", "calculate_infterface.data", "AddInt");
    mesg2.append(3, 4);

    cout<<"3 async_send begin"<<endl;
    conn->async_send(mesg2, [](boost::system::error_code ec, message::message& ret) {
        cout << "async_send callback
";
        if (ec)
        {
            cout<<"error with async_send"<<endl;
            return;
        }
        int data = 0;
        ret.read(data);
        cout<<"ret data="<<data<<endl;
    });
    cout<<"4 async_send end"<<endl;
}
 
int main()
{
    boost::asio::io_context io;
    auto conn = make_shared<sdbusplus::asio::connection>(io);
    cout<<"asyncCallSend begin"<<endl;
    asyncCallSend(conn);
    cout<<"asyncCallSend end"<<endl;
    io.run();
    return 0;
}
编译程序:
g++ -o async_send ./async_send.cpp -lsdbusplus -lsystemd

运行程序输出:
asyncCallSend begin
1 async_send begin
2 async_send end
3 async_send begin
4 async_send end
asyncCallSend end
async_send callback
ret data=3
async_send callback
ret data=7

可以看出asyncCallSend被调用后,函数体执行时,相当于注册了两个回调函数,函数体顺序执行后,再通过回调从service的method拿到了返回值。