CARLA
 
载入中...
搜索中...
未找到
test_rpc.cpp
浏览该文件的文档.
1// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
2// de Barcelona (UAB).
3//
4// This work is licensed under the terms of the MIT license.
5// For a copy, see <https://opensource.org/licenses/MIT>.
6
7#include "test.h"
8//包含一个自定义的头文件"test.h"。
9// 通常在"test.h"里会有当前源文件所需的函数声明、结构体定义、宏定义等内容,方便在本文件中调用相关功能。
10#include <carla/MsgPackAdaptors.h>//包含来自名为"carla"的项目(可能是库等)下的头文件。
11#include <carla/ThreadGroup.h>//同样是从"carla"项目中引入头文件,此头文件大概率是关于线程组(ThreadGroup)的相关定义。
12// 例如可能包含创建、管理线程组的类,或者操作线程组的函数等,方便在代码中进行多线程相关的编程操作。
13#include <carla/rpc/Actor.h>//
14#include <carla/rpc/Client.h>
15#include <carla/rpc/Response.h>
16#include <carla/rpc/Server.h>
17
18#include <thread>
19
20using namespace carla::rpc;
21using namespace std::chrono_literals;
22// 测试 RPC 功能的编译测试
23TEST(rpc, compilation_tests) {
24 // 创建一个服务器实例
25 Server server(TESTING_PORT);
26 // 绑定同步方法,无参数,返回 2.0f
27 server.BindSync("bind00", []() { return 2.0f; });
28 // 绑定同步方法,一个 int 参数,返回传入的参数
29 server.BindSync("bind01", [](int x) { return x; });
30 // 绑定同步方法,两个参数(int 和 float),返回 0.0
31 server.BindSync("bind02", [](int, float) { return 0.0; });
32 // 绑定同步方法,四个参数(int、float、double、char),无返回值
33 server.BindSync("bind03", [](int, float, double, char) {});
34}
35// 测试服务器绑定同步方法并在游戏线程上运行
36TEST(rpc, server_bind_sync_run_on_game_thread) {
37 // 获取当前主线程的 ID
38 const auto main_thread_id = std::this_thread::get_id();
39// 定义端口号,如果 TESTING_PORT 不为 0 则使用 TESTING_PORT,否则使用 2017
40 const uint16_t port = (TESTING_PORT != 0u ? TESTING_PORT : 2017u);
41// 创建服务器实例
42 Server server(port);
43// 绑定一个同步方法,接收两个 int 参数,返回它们的和,并检查当前线程是否为主线程
44 server.BindSync("do_the_thing", [=](int x, int y) -> int {
45 EXPECT_EQ(std::this_thread::get_id(), main_thread_id);
46 return x + y;
47 });
48// 异步运行服务器,传入一个线程数参数
49 server.AsyncRun(1u);
50// 创建一个原子布尔变量,用于标记任务是否完成
51 std::atomic_bool done{false};
52// 创建线程组
53 carla::ThreadGroup threads;
54 // 创建一个线程,在该线程中执行以下逻辑
55 threads.CreateThread([&]() {
56 // 创建客户端实例,连接到本地主机和指定端口
57 Client client("localhost", port);
58 // 循环执行 300 次
59 for (auto i = 0; i < 300; ++i) {
60 // 调用服务器上的方法,传入两个参数,并将结果转换为 int 类型,检查结果是否正确
61 auto result = client.call("do_the_thing", i, 1).as<int>();
62 EXPECT_EQ(result, i + 1);
63 }
64 // 标记任务完成
65 done = true;
66 });
67// 循环计数器
68 auto i = 0u;
69 // 循环执行,直到任务完成或达到一定次数
70 for (; i < 1'000'000u; ++i) {
71 // 在服务器上同步运行一段时间(2 毫秒)
72 server.SyncRunFor(2ms);
73 // 如果任务完成,则跳出循环
74 if (done) {
75 break;
76 }
77 }
78 // 输出服务器在游戏线程上运行的次数
79 std::cout << "game thread: run " << i << " slices.\n";
80 // 断言任务已完成
81 ASSERT_TRUE(done);
82}
void CreateThread(F &&functor)
Definition ThreadGroup.h:31
一个RPC服务器,可以将功能绑定为同步或异步运行。
Definition rpc/Server.h:34
包含CARLA客户端相关类和函数的命名空间。
constexpr uint16_t TESTING_PORT
Definition test.h:24
TEST(rpc, compilation_tests)
Definition test_rpc.cpp:23