隐语yacl通信示例

隐语平台yacl通信实例代码如下,环境中两台通信机器ip地址分别为172.18.0.2和172.18.0.3。

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <memory>
#include <type_traits>
#include <variant>
#include <unistd.h>
#include <future>
#include <limits>

#include "fmt/format.h"
#include "gtest/gtest.h"

#include "yacl/link/context.h"
#include "yacl/link/link.h"
#include "yacl/link/factory.h"

class FactoryTest{
 public:
  FactoryTest()
  {
    static int desc_count = 0;
    contexts_.resize(2);
    yacl::link::ContextDesc desc;
    desc.id = fmt::format("world_{}", desc_count++);
    desc.parties.push_back(yacl::link::ContextDesc::Party("alice", "172.18.0.2:63927"));
    desc.parties.push_back(yacl::link::ContextDesc::Party("bob", "172.18.0.2:63921"));

    auto create_brpc = [&](int self_rank) {
      contexts_[self_rank] = yacl::link::FactoryBrpc().CreateContext(desc, self_rank);
      //contexts_[self_rank]->ConnectToMesh();
    };

    std::vector<std::future<void>> creates;
    creates.push_back(std::async(create_brpc, 0));

    for (auto& f : creates) {
      f.get();
    }
    std::cout << "Connect to Bob successfully\n";
  }

  void work()
  {
    auto test = [&](int self_rank)
    {
      int dst_rank = 1 - self_rank;
      this->contexts_[self_rank]->SendAsync(dst_rank, "Hello I am 0", "test");

      yacl::Buffer r = this->contexts_[self_rank]->Recv(dst_rank, "test");
      std::string r_str(r.data<const char>(), r.size());
      std::cout << self_rank << " Receive "  << r_str << '\n';
    };

    std::vector<std::future<void>> tests;
    tests.push_back(std::async(test, 0));
    tests.push_back(std::async(test, 1));

    for (auto& f : tests) {
      f.get();
    }
  }

  ~FactoryTest()
  {
    auto wait = [&](int self_rank) {
      contexts_[self_rank]->WaitLinkTaskFinish();
    };
    
    std::vector<std::future<void>> waits;
    waits.push_back(std::async(wait, 0));

    for (auto& f : waits) {
      f.get();
    }
  }

  std::vector<std::shared_ptr<yacl::link::Context>> contexts_;
};

int main() {
  FactoryTest F;
  F.work();
  return 0;
}

另一边的代码类似,只是编号self_rank不同。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值