Total: 24 files changed+6034-144
A.codex+0-0
The file is empty
MCMakeLists.txt+5-3File content is under review, please try again later
MREADME.md+23-5
@@ -26,7 +26,7 @@
26 26 
27- 对外头文件清晰,适合 C / C++ 混合项目直接接入。27- 对外头文件清晰,适合 C / C++ 混合项目直接接入。
28- 分布式锁支持 `S`、`SX`、`X` 三种模式,并提供超时、延迟释放、可选递归和故障恢复接口。28- 分布式锁支持 `S`、`SX`、`X` 三种模式,并提供超时、延迟释放、可选递归和故障恢复接口。
29-- 通信队列支持多节点、多优先级 Ring、同步/异步回调、就绪状态检查。29+- 通信队列支持多节点、多优先级 Ring、同步/异步回调、就绪状态检查,并提供发送侧流控、拥塞状态查询和边缘触发维测日志。
lan_xin
lan_xinlan_xinApr 29

.codex去掉

likedislike
30- 事务资源直接封装共享内存上的 `std::atomic<uint64_t>`,适合计数器、状态位、序号分配等场景。30- 事务资源直接封装共享内存上的 `std::atomic<uint64_t>`,适合计数器、状态位、序号分配等场景。
31- 仓库内附带 `sample_code/` 和 `test/`,便于快速验证接口行为。31- 仓库内附带 `sample_code/` 和 `test/`,便于快速验证接口行为。
32 32 
@@ -42,7 +42,7 @@
42| 模块 | 对外头文件 | 核心能力 | 典型场景 |42| 模块 | 对外头文件 | 核心能力 | 典型场景 |
43| --- | --- | --- | --- |43| --- | --- | --- | --- |
44| 分布式锁 | `include/ub_dist_lock.h` | 共享内存读写锁,支持 `S/SX/X`、超时、递归、故障恢复 | 元数据锁、事务并发控制 |44| 分布式锁 | `include/ub_dist_lock.h` | 共享内存读写锁,支持 `S/SX/X`、超时、递归、故障恢复 | 元数据锁、事务并发控制 |
45-| 通信队列 | `include/ub_dist_comm_queue.h` | 共享内存消息队列,支持多 Ring、同步/异步回调 | 节点间通知、事件投递 |45+| 通信队列 | `include/ub_dist_comm_queue.h` | 共享内存消息队列,支持多 Ring、同步/异步回调 | 节点间通知、事件投递、消息流控 |
46| 事务资源 | `include/ub_dist_tx_res.h` | 基于共享内存的原子 `uint64_t` 资源访问 | 计数器、状态位、全局序号 |46| 事务资源 | `include/ub_dist_tx_res.h` | 基于共享内存的原子 `uint64_t` 资源访问 | 计数器、状态位、全局序号 |
47 47 
48### 内部关系48### 内部关系
@@ -144,7 +144,7 @@ sh build.sh -j 16
144- `dist/release/lib/libubs-atomic.so`144- `dist/release/lib/libubs-atomic.so`
145- `dist/debug/lib/libubs-atomic.so`145- `dist/debug/lib/libubs-atomic.so`
146 146 
147-RPM 打包产物通过 `sh build.sh package` 生成,文件名格式为 `ubs-atomic-{version}.{ARCH}.rpm`,例如 `ubs-atomic-1.0.aarch64.rpm`。147+RPM 打包产物通过 `sh build.sh package` 生成,文件名格式为 `ubs-atomic-{version}-{release}.{ARCH}.rpm`,默认从 `ubs-atomic-1.0.0-1.aarch64.rpm` 开始;下个 release 可使用 `sh build.sh package -V 1.0.0-2`。
148 148 
149### 3. 在你的工程中链接149### 3. 在你的工程中链接
150 150 
@@ -352,6 +352,19 @@ int main()
352| `ub_comm_conf_t` | `cpu_id`, `max_nodes`, `current_node_id`, `num_rings` | 队列实例全局配置 |352| `ub_comm_conf_t` | `cpu_id`, `max_nodes`, `current_node_id`, `num_rings` | 队列实例全局配置 |
353| `message_header_t` | `src_thread_id`, `dest_node_id`, `msg_type`, `priority` | 消息头 |353| `message_header_t` | `src_thread_id`, `dest_node_id`, `msg_type`, `priority` | 消息头 |
354| `message_t` | `header`, `body` | 完整消息 |354| `message_t` | `header`, `body` | 完整消息 |
355+| `ub_comm_queue_status_t` | `used`, `total`, `free`, `state`, `congestion_threshold`, `max_depth` | Ring 状态与流控水位快照 |
356+ 
357+#### 发送流控
358+ 
359+发送接口按固定优先级判定:
360+ 
361+1. Ring 已满:无法写入,返回 `UB_COMM_ERR_RING_FULL`。
362+2. Ring 已达到拥塞阈值:消息已写入,返回 `UB_COMM_SEND_CONGESTED`。
363+3. Ring 未拥塞:消息已写入,返回 `UB_COMM_OK`。
364+ 
365+默认拥塞阈值为 Ring 容量的 `80%`。初始化接口不暴露阈值配置;如需调整,初始化后调用 `ub_comm_queue_set_congestion_threshold` 修改本节点本地 Ring。防抖采样为内部策略,不作为对外配置项。
366+ 
367+流控日志默认开启且为边缘触发,只在首次进入拥塞和从拥塞恢复时打印。普通模式日志包含 `ring`、`ts_us`、`used`、`total`、`threshold`、`max_depth` 等字段;定义 `UB_COMM_QUEUE_ENABLE_DEBUG_STATS` 后会额外包含计数类维测字段。
355 368 
356#### 接口说明369#### 接口说明
357 370 
@@ -359,8 +372,9 @@ int main()
359| --- | --- | --- |372| --- | --- | --- |
360| `ub_comm_queue_init` | 初始化通信实例 | 需要初始化区和所有节点 Ring 映射 |373| `ub_comm_queue_init` | 初始化通信实例 | 需要初始化区和所有节点 Ring 映射 |
361| `ub_comm_queue_deinit` | 销毁通信实例 | 释放内部线程和资源 |374| `ub_comm_queue_deinit` | 销毁通信实例 | 释放内部线程和资源 |
362-| `ub_comm_queue_send` | 发送消息 | `msg_type` 不能使用系统保留类型 |375+| `ub_comm_queue_send` | 发送消息 | 返回 `UB_COMM_OK` / `UB_COMM_SEND_CONGESTED` 表示写入成功,负数表示失败 |
363-| `ub_comm_queue_recv` | 拉取消息到用户缓冲区 | 回调模式之外的主动接收接口 |376+| `ub_comm_queue_get_status` | 查询 Ring 状态 | 返回使用量、容量、空闲数、状态和阈值;debug 宏开启后包含统计计数 |
377+| `ub_comm_queue_set_congestion_threshold` | 修改本地 Ring 拥塞阈值 | 运行期调整本节点指定优先级 Ring 的水位 |
364| `ub_comm_queue_check_ready` | 检查目标节点是否已就绪 | 发消息前可用于探活 / 同步 |378| `ub_comm_queue_check_ready` | 检查目标节点是否已就绪 | 发消息前可用于探活 / 同步 |
365| `ub_comm_queue_register_process_func` | 注册消息处理回调 | 支持 `UB_FUNC_SYNC` 和 `UB_FUNC_ASYNC` |379| `ub_comm_queue_register_process_func` | 注册消息处理回调 | 支持 `UB_FUNC_SYNC` 和 `UB_FUNC_ASYNC` |
366 380 
@@ -372,6 +386,8 @@ int main()
372- 业务 Ring 的优先级级数实际上也受限于内部实现的最大优先级数 `8`。386- 业务 Ring 的优先级级数实际上也受限于内部实现的最大优先级数 `8`。
373- 所有节点对 `init_region`、`ring_descs`、Ring 布局的理解必须完全一致,否则会出现互操作错误。387- 所有节点对 `init_region`、`ring_descs`、Ring 布局的理解必须完全一致,否则会出现互操作错误。
374- `msg_type = 0xFF` 和 `0xFE` 为内部保留类型,不应作为业务消息类型使用。388- `msg_type = 0xFF` 和 `0xFE` 为内部保留类型,不应作为业务消息类型使用。
389+- `UB_COMM_SEND_CONGESTED` 是成功返回码,不应按发送失败处理;调用方可据此降低发送速率或触发上层反压。
390+- 状态查询基于本地原子快照,适合维测和流控策略参考,不应作为强一致队列长度使用。
375 391 
376#### 回调模型392#### 回调模型
377 393 
@@ -405,6 +421,8 @@ int main()
405- `sample_code/ub_dist_tx_res/`:单节点、多线程、主从模式下的原子资源示例。421- `sample_code/ub_dist_tx_res/`:单节点、多线程、主从模式下的原子资源示例。
406- `sample_code/share_mem/`:共享内存创建和使用示例。422- `sample_code/share_mem/`:共享内存创建和使用示例。
407 423 
424+消息队列的内部初始化流程、发送快路径、回调热注册、远端缓存和下线广播实现说明见 `src/ub_comm_queue/README.md`。
425+ 
408这些样例依赖 `ubsmem` SDK,适合在实际共享内存环境中联调。426这些样例依赖 `ubsmem` SDK,适合在实际共享内存环境中联调。
409 427 
410## 测试说明428## 测试说明
Mbuild.sh+23-1
@@ -85,6 +85,8 @@ build_type="Release"
85build_dir="dist"85build_dir="dist"
86std="17" # CXX 语言版本86std="17" # CXX 语言版本
87generator="Unix Makefiles"87generator="Unix Makefiles"
88+package_version="1.0.0"
89+package_release="1"
88 90 
89enable_coverage="OFF"91enable_coverage="OFF"
90enable_test="OFF"92enable_test="OFF"
@@ -200,6 +202,24 @@ function parse_args() {
200 export VERBOSE=1202 export VERBOSE=1
201 shift203 shift
202 ;;204 ;;
205+ -V | --deploy-version)
206+ if [[ $# -gt 1 && "$2" != "-"* ]]; then
207+ deploy_version="$2"
208+ if [[ "$deploy_version" =~ ^([0-9]+(\.[0-9]+){2})-([0-9]+)$ ]]; then
209+ package_version="${BASH_REMATCH[1]}"
210+ package_release="${BASH_REMATCH[3]}"
211+ elif [[ "$deploy_version" =~ ^[0-9]+$ ]]; then
212+ package_release="$deploy_version"
213+ else
214+ log_info "Error: Invalid deploy version '$deploy_version'. Use 1.0.0-1 or release number like 1."
215+ exit 1
216+ fi
217+ shift 2
218+ else
219+ log_info "Error: Argument required after -V | --deploy-version."
220+ exit 1
221+ fi
222+ ;;
203 --skip-run-tests)223 --skip-run-tests)
204 skip_run_tests='ON'224 skip_run_tests='ON'
205 shift225 shift
@@ -320,6 +340,8 @@ function build_cmake() {
320 -DCMAKE_CXX_STANDARD="${std}" \340 -DCMAKE_CXX_STANDARD="${std}" \
321 -DCMAKE_TOOLCHAIN_FILE="${toolchain_file}" \341 -DCMAKE_TOOLCHAIN_FILE="${toolchain_file}" \
322 -DCMAKE_INSTALL_PREFIX=${build_dir}/install \342 -DCMAKE_INSTALL_PREFIX=${build_dir}/install \
343+ -DUBS_ATOMIC_VERSION=${package_version} \
344+ -DUBS_ATOMIC_PACKAGE_RELEASE=${package_release} \
323 -DBUILD_TESTS=${enable_test} \345 -DBUILD_TESTS=${enable_test} \
324 -DENABLE_COVERAGE=${enable_coverage} \346 -DENABLE_COVERAGE=${enable_coverage} \
325 -DASAN_BUILD=${enable_asan} \347 -DASAN_BUILD=${enable_asan} \
@@ -364,4 +386,4 @@ build_cmake # 执行 CMake 构建
364 386 
365END_TIME=$(date +%s.%N)387END_TIME=$(date +%s.%N)
366EXEC_TIME=$(echo "scale=3; ($END_TIME - $START_TIME) / 1" | bc)388EXEC_TIME=$(echo "scale=3; ($END_TIME - $START_TIME) / 1" | bc)
367-echo -e $(date +"[%Y-%m-%d %H:%M]"): "\033[32m" Build complated in "$EXEC_TIME"s '\033[0m'389+echo -e $(date +"[%Y-%m-%d %H:%M]"): "\033[32m" Build complated in "$EXEC_TIME"s '\033[0m'
Minclude/ub_dist_comm_queue.h+63-2File content is under review, please try again later
Msample_code/ub_comm_queue/README.md+230-2File content is under review, please try again later
@@ -0,0 +1,655 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3+ *
4+ * Lightweight smoke tests for ub_comm_queue flow-control status APIs.
5+ */
6+ 
7+#include <errno.h>
8+#include <fcntl.h>
9+#include <getopt.h>
10+#include <inttypes.h>
11+#include <stdio.h>
12+#include <stdlib.h>
13+#include <string.h>
14+#include <sys/mman.h>
15+#include <sys/stat.h>
16+#include <sys/types.h>
17+#include <unistd.h>
18+ 
19+#include <atomic>
20+#include <chrono>
21+#include <cstdint>
22+#include <thread>
23+#include <vector>
24+ 
25+#include "ub_dist_comm_queue.h"
26+#include "ubs_mem.h"
27+#include "ubs_mem_def.h"
28+ 
29+using namespace std::chrono_literals;
30+ 
31+namespace {
32+ 
33+constexpr uint8_t NODE_A = 0;
34+constexpr uint8_t NODE_B = 1;
35+constexpr uint8_t MAX_NODES = 2;
36+constexpr unsigned long SHM_MAP_MB = 1024;
37+constexpr size_t INIT_REGION_SIZE = 1024 * 1024;
38+constexpr size_t RING_REGION_SIZE = 64 * 1024 * 1024;
39+constexpr uint32_t DEFAULT_CAPACITY = 1024;
40+constexpr uint32_t MAX_MSG_SIZE = 256;
41+constexpr uint8_t CTRL_PRIORITY = 1;
42+constexpr uint8_t MSG_CTRL = 210;
43+constexpr uint8_t MSG_ACK = 211;
44+ 
45+enum class CaseId : uint32_t {
46+ CASE1_LOCAL_DEINIT = 1,
47+ CASE2_REMOTE_DEINIT = 2,
48+ CASE3_TWO_RINGS = 3,
49+ CASE4_SEVEN_RINGS = 4,
50+};
51+ 
52+enum CtrlCmd : uint32_t {
53+ CMD_SET_THRESHOLD = 1,
54+ CMD_QUERY_A_TWO_RINGS = 2,
55+ CMD_STOP = 3,
56+};
57+ 
58+#pragma pack(push, 1)
59+struct CtrlMessage {
60+ uint32_t cmd;
61+ uint32_t seq;
62+ uint32_t priority;
63+ uint32_t value;
64+};
65+ 
66+struct AckMessage {
67+ uint32_t cmd;
68+ uint32_t seq;
69+ int32_t ret;
70+ uint64_t observed;
71+};
72+#pragma pack(pop)
73+ 
74+static_assert(sizeof(CtrlMessage) <= MAX_MSG_SIZE - sizeof(message_header_t), "CtrlMessage body too large");
75+static_assert(sizeof(AckMessage) <= MAX_MSG_SIZE - sizeof(message_header_t), "AckMessage body too large");
76+ 
77+struct Context {
78+ ub_shm_comm_t *handle = nullptr;
79+ uint8_t self = NODE_A;
80+ uint8_t peer = NODE_B;
81+ std::atomic<bool> stop{false};
82+ std::atomic<uint32_t> next_seq{1};
83+ std::atomic<uint32_t> ack_seq{0};
84+ std::atomic<int32_t> ack_ret{0};
85+ std::atomic<uint64_t> ack_observed{0};
86+};
87+ 
88+char g_role = 'A';
89+CaseId g_case = CaseId::CASE1_LOCAL_DEINIT;
90+char g_sender_shm_name[64] = "smoke_sender";
91+char g_receiver_shm_name[64] = "smoke_receiver";
92+uint32_t g_capacity = DEFAULT_CAPACITY;
93+int g_wait_peer_timeout_s = 20;
94+int g_log_level = LOG_LEVEL_ERROR;
95+Context g_ctx;
96+ 
97+int stdout_logger(int level, const char *file, const char *func, uint32_t line, const char *message)
98+{
99+ (void)func;
100+ fprintf(stdout, "[%s:%u] [L%d] %s\n", file, line, level, message);
Asample_code/ub_comm_queue/ping.cpp+401-0File content is under review, please try again later
@@ -0,0 +1,279 @@
1+ 
2+#include <stdio.h>
3+#include <stdlib.h>
4+#include <string.h>
5+#include <unistd.h>
6+#include <atomic>
7+#include <chrono>
8+#include <thread>
9+#include <vector>
10+#include <getopt.h>
11+#include <algorithm>
12+#include <numeric>
13+#include <mutex>
14+#include <cinttypes>
15+#include <errno.h>
16+#include <stdio.h>
17+#include <stdlib.h>
18+#include <string.h>
19+#include <sys/ipc.h>
20+#include <sys/mman.h>
21+#include <sys/shm.h>
22+#include <sys/types.h>
23+#include <unistd.h>
24+#include <algorithm>
25+#include <atomic>
26+#include <chrono>
27+#include <cstdlib>
28+#include <cstring>
29+#include <iostream>
30+#include <mutex>
31+#include <set>
32+#include <thread>
33+#include <vector>
34+#include <fcntl.h>
35+#include <sys/stat.h>
36+#include <cstddef>
37+#include <future>
38+ 
39+#include "ub_dist_comm_queue.h"
40+#include "ubs_mem.h"
41+#include "ubs_mem_def.h"
42+ 
43+using namespace std::chrono_literals;
44+ 
45+enum MsgType : uint8_t {
46+ TYPE_PING = 100,
47+ TYPE_PONG = 101
48+};
49+ 
50+int my_stdout_logger(int level, const char *file, const char *func, uint32_t line, const char *message)
51+{
52+ const char *level_str = "UNKNOWN";
53+ switch (level) {
54+ case 0:
55+ level_str = "DEBUG";
56+ break;
57+ case 1:
58+ level_str = "INFO";
59+ break;
60+ case 2:
61+ level_str = "WARN";
62+ break;
63+ case 3:
64+ level_str = "ERROR";
65+ break;
66+ case 4:
67+ level_str = "CRITICAL";
68+ break;
69+ default:
70+ break;
71+ }
72+ 
73+ time_t now = time(0);
74+ char *time_str = ctime(&now);
75+ time_str[strlen(time_str) - 1] = '\0';
76+ 
77+ fprintf(stdout, "[%s] [%s:%u] [%s] %s\n", time_str, file, line, level_str, message);
78+ 
79+ return 0;
80+}
81+ 
82+static const size_t RING_CAPACITY = 1024;
83+static const size_t SLOT_SIZE = 1024;
84+static const uint32_t MIN_BODY_LENGTH = 48;
85+ 
86+static unsigned long g_shm_size_mb = 128;
87+static uint64_t NodeA = 0;
88+static uint64_t NodeB = 1;
89+// 改为可修改的全局变量
90+static char kSenderShmName[64] = "shm_node0_export";
91+static char kReceiverShmName[64] = "shm_node1_export";
92+ 
93+static uint64_t g_expect = 0;
94+ 
95+#pragma pack(push, 1)
96+struct PingPongMsg {
97+ uint32_t msg_id;
98+ int64_t A_send_time;
99+ int64_t B_recv_time;
100+ int64_t B_send_time;
101+ int64_t A_recv_time;
102+ char padding[12];
103+};
104+#pragma pack(pop)
105+static_assert(sizeof(PingPongMsg) == MIN_BODY_LENGTH, "PingPongMsg must be 48 bytes");
106+ 
107+static inline int64_t get_ns() {
108+ return (int64_t)std::chrono::duration_cast<std::chrono::nanoseconds>(
109+ std::chrono::steady_clock::now().time_since_epoch()).count();
110+}
111+ 
112+static std::atomic<uint64_t> g_ping_recv{0};
113+static std::atomic<uint64_t> g_pong_send{0};
114+static std::atomic<int64_t> g_b_process_sum{0};
115+ 
116+static void on_ping_msg(const message_t *msg, void *ctx) {
117+ const int64_t t_recv = get_ns();
118+ if (msg->header.msg_type != TYPE_PING || msg->header.body_length != MIN_BODY_LENGTH) {
119+ return;
120+ }
121+ 
122+ PingPongMsg local;
123+ memcpy(&local, msg->body, sizeof(local));
124+ 
125+ local.B_recv_time = t_recv;
126+ local.B_send_time = get_ns();
127+ 
128+ message_t pong{};
129+ pong.header.dest_node_id = NodeA;
130+ pong.header.src_node_id = NodeB;
131+ pong.header.msg_type = TYPE_PONG;
132+ pong.header.priority = 1;
133+ pong.header.body_length = MIN_BODY_LENGTH;
134+ pong.body = (char*)&local;
135+ 
136+ ub_shm_comm_t* handlep = (ub_shm_comm_t*)ctx;
137+ 
138+ for (;;) {
139+ int ret = ub_comm_queue_send(handlep, &pong);
140+ if (ret >= 0) break;
141+#if defined(__aarch64__)
142+ asm volatile("yield" ::: "memory");
143+#endif
144+ }
145+ 
146+ g_ping_recv.fetch_add(1, std::memory_order_relaxed);
147+ g_pong_send.fetch_add(1, std::memory_order_relaxed);
148+ g_b_process_sum.fetch_add(local.B_send_time - local.B_recv_time, std::memory_order_relaxed);
149+}
150+ 
151+static int init_ub_shm() {
152+ ubsmem_options_t opts{};
153+ int ret = ubsmem_init_attributes(&opts);
154+ if (ret != UBSM_OK) {
155+ fprintf(stderr, "Failed to initialize ubsmem attributes!\n");
156+ return -1;
157+ }
158+ ret = ubsmem_initialize(&opts);
159+ if (ret != UBSM_OK) {
160+ fprintf(stderr, "Failed to initialize ubsmem!\n");
161+ return -1;
162+ }
163+ ubsmem_regions_t regions = {0};
164+ ret = ubsmem_lookup_regions(&regions);
165+ if (ret != UBSM_OK) {
166+ fprintf(stderr, "Failed to look up node information!\n");
167+ return -1;
168+ }
169+ return 0;
170+}
171+ 
172+static int map_ub_shm(const char *shm_name, void *&addr) {
173+ const unsigned long length = g_shm_size_mb * 1024UL * 1024UL;
174+ int ret = ubsmem_shmem_map(nullptr, length, PROT_READ | PROT_WRITE, MAP_SHARED, shm_name, 0, &addr);
175+ if (ret != 0) {
176+ fprintf(stderr, "Failed to map shared memory '%s'! ret=%d\n", shm_name, ret);
177+ return -1;
178+ }
179+ fprintf(stdout, "Mapped '%s' at %p\n", shm_name, addr);
180+ return 0;
181+}
182+ 
183+// 新增:打印帮助信息(包含shm参数)
184+static void print_help(const char* prog) {
185+ printf("Usage: %s [-n expect_count(0=run forever)] [-s sender_shm] [-r receiver_shm] [-h]\n", prog);
186+ printf(" -n: expect pong count (0=forever, default: 0)\n");
187+ printf(" -s: sender shared memory name (default: shm_node0_export)\n");
188+ printf(" -r: receiver shared memory name (default: shm_node1_export)\n");
189+ printf(" -h: show help\n");
190+}
191+ 
192+int main(int argc, char** argv) {
193+ int opt;
194+ // 新增:解析 -s -r 参数
195+ while ((opt = getopt(argc, argv, "n:s:r:h")) != -1) {
196+ switch (opt) {
197+ case 'n': g_expect = strtoull(optarg, nullptr, 10); break;
198+ case 's': strncpy(kSenderShmName, optarg, sizeof(kSenderShmName)-1); break;
199+ case 'r': strncpy(kReceiverShmName, optarg, sizeof(kReceiverShmName)-1); break;
200+ case 'h': print_help(argv[0]); return 0;
201+ default: print_help(argv[0]); return -1;
202+ }
203+ }
204+ ub_atomic_set_log_level(LOG_LEVEL_ERROR);
205+ ub_atomic_register_log_func(my_stdout_logger);
206+ 
207+ printf("===== B Node (Ponger) ===== expect=%" PRIu64 " (0=forever)\n", g_expect);
208+ printf("sender_shm=%s receiver_shm=%s\n", kSenderShmName, kReceiverShmName);
209+ 
210+ if (init_ub_shm() != 0) return -1;
211+ 
212+ void *sender_shm_base = nullptr;
213+ if (map_ub_shm(kSenderShmName, sender_shm_base) != 0) return -1;
214+ 
215+ void *receiver_shm_base = nullptr;
216+ if (map_ub_shm(kReceiverShmName, receiver_shm_base) != 0) return -1;
217+ 
218+ ub_shm_comm_t handle = nullptr;
219+ const size_t init_size = 1024 * 1024;
220+ const size_t ring_size = 1900800;
221+ 
222+ void* init_area = sender_shm_base;
223+ void* ring_area_A = (char*)sender_shm_base + init_size;
224+ void* ring_area_B = (char*)receiver_shm_base;
225+ 
226+ ub_ring_desc_t ring_desc = {RING_CAPACITY, SLOT_SIZE, 1};
227+ ub_comm_conf_t conf = {
228+ .cpu_id = 200,
229+ .max_nodes = 2,
230+ .current_node_id = NodeB,
231+ .num_rings = 1,
232+ .ring_descs = &ring_desc
233+ };
234+ 
235+ ub_shm_area_t init_shm_area;
236+ init_shm_area.ptr = init_area;
237+ init_shm_area.size = init_size;
238+ 
239+ ub_ring_region_info_t ring_info[2];
240+ ring_info[0].node_id = NodeA;
241+ ring_info[0].region.ptr = ring_area_A;
242+ ring_info[0].region.size = ring_size;
243+ ring_info[1].node_id = NodeB;
244+ ring_info[1].region.ptr = ring_area_B;
245+ ring_info[1].region.size = ring_size;
246+ 
247+ ub_ring_region_map_t ring_map{ ring_info, 2 };
248+ 
249+ if (ub_comm_queue_init(&handle, &init_shm_area, &ring_map, &conf) != 0) {
250+ fprintf(stderr, "ub_comm_queue_init failed\n");
251+ return -1;
252+ }
253+ 
254+ ub_shm_comm_t* handlep = &handle;
255+ ub_comm_queue_register_process_func(handlep, TYPE_PING, UB_FUNC_SYNC, on_ping_msg, handlep);
256+ 
257+ printf("B ready.\n");
258+ 
259+ while (true) {
260+ if (g_expect > 0 && g_pong_send.load(std::memory_order_relaxed) >= g_expect) break;
261+ std::this_thread::sleep_for(1s);
262+ const auto cnt = g_pong_send.load(std::memory_order_relaxed);
263+ if (cnt > 0) {
264+ double avg = (double)g_b_process_sum.load(std::memory_order_relaxed) / (double)cnt;
265+ printf("[B] pong_sent=%" PRIu64 " avg_b_process(ns)=%.2f\n", cnt, avg);
266+ }
267+ }
268+ 
269+ printf("\n===== B Summary =====\n");
270+ printf("ping_recv=%" PRIu64 " pong_sent=%" PRIu64 "\n",
271+ g_ping_recv.load(), g_pong_send.load());
272+ if (g_pong_send.load() > 0) {
273+ double avg = (double)g_b_process_sum.load() / (double)g_pong_send.load();
274+ printf("avg_b_process(ns)=%.2f\n", avg);
275+ }
276+ 
277+ ub_comm_queue_deinit(&handle);
278+ return 0;
279+}
@@ -0,0 +1,157 @@
1+#!/usr/bin/env bash
2+ 
3+set -euo pipefail
4+ 
5+ROOT_DIR=$(cd "$(dirname "$0")/../.." && pwd)
6+SAMPLE_DIR="${ROOT_DIR}/sample_code/ub_comm_queue"
7+BUILD_DIR="${BUILD_DIR:-/tmp/ub_comm_queue_flow_validation}"
8+BIN="${BIN:-${SAMPLE_DIR}/flow_control_queue_test}"
9+SRC="${SAMPLE_DIR}/flow_control_queue_test.cpp"
10+SHM_CREATOR="${SHM_CREATOR:-./node_ubsm_shm_creator}"
11+CXX="${CXX:-g++}"
12+BUILD_LOCAL="${BUILD_LOCAL:-0}"
13+ 
14+SENDER_SHM="${SENDER_SHM:-flow_sender_$$}"
15+RECEIVER_SHM="${RECEIVER_SHM:-flow_receiver_$$}"
16+SENDER_HOST="${SENDER_HOST:-slot1}"
17+RECEIVER_HOST="${RECEIVER_HOST:-slot2}"
18+CASE_NAME="${CASE_NAME:-all}"
19+CAPACITY="${CAPACITY:-64}"
20+THRESHOLD="${THRESHOLD:-50}"
21+PERF_MESSAGES="${PERF_MESSAGES:-20000}"
22+WAIT_SECONDS="${WAIT_SECONDS:-20}"
23+LOG_LEVEL="${LOG_LEVEL:-3}"
24+RUN_MATRIX="${RUN_MATRIX:-0}"
25+CAPACITY_MATRIX="${CAPACITY_MATRIX:-64 256 2048}"
26+PERF_MESSAGES_MATRIX="${PERF_MESSAGES_MATRIX:-4096 8192 4096}"
27+ 
28+CXXFLAGS_EXTRA="${CXXFLAGS_EXTRA:-}"
29+LDFLAGS_EXTRA="${LDFLAGS_EXTRA:-}"
30+COMM_INCLUDE="${COMM_INCLUDE:-${ROOT_DIR}/include}"
31+COMM_SRC_INCLUDE="${COMM_SRC_INCLUDE:-${ROOT_DIR}/src/ub_comm_queue}"
32+UBSM_INCLUDE="${UBSM_INCLUDE:-/usr/local/ubs_mem/include}"
33+COMM_LIB_DIR="${COMM_LIB_DIR:-/usr/lib64}"
34+UBSM_LIB_DIR="${UBSM_LIB_DIR:-/usr/local/ubs_mem/lib}"
35+CREATED_SHMS=()
36+ 
37+cleanup()
38+{
39+ local code=$?
40+ if [[ -n "${B_PID:-}" ]]; then
41+ if kill -0 "${B_PID}" 2>/dev/null; then
42+ kill "${B_PID}" 2>/dev/null || true
43+ fi
44+ wait "${B_PID}" 2>/dev/null || true
45+ fi
46+ if [[ -x "${SHM_CREATOR}" ]]; then
47+ for item in "${CREATED_SHMS[@]:-}"; do
48+ local host="${item%%:*}"
49+ local shm="${item#*:}"
50+ "${SHM_CREATOR}" delete "${host}" "${shm}" >/dev/null 2>&1 || true
51+ done
52+ fi
53+ exit "${code}"
54+}
55+trap cleanup EXIT
56+ 
57+if [[ "${BUILD_LOCAL}" == "1" ]]; then
58+ mkdir -p "$(dirname "${BIN}")"
59+ 
60+ echo "[build] ${BIN}"
61+ "${CXX}" -O2 -g -std=c++17 ${CXXFLAGS_EXTRA} -o "${BIN}" "${SRC}" \
62+ -I"${COMM_INCLUDE}" \
63+ -I"${COMM_SRC_INCLUDE}" \
64+ -I"${UBSM_INCLUDE}" \
65+ -L"${COMM_LIB_DIR}" \
66+ -L"${UBSM_LIB_DIR}" \
67+ ${LDFLAGS_EXTRA} \
68+ -lubturbo_tdsql \
69+ -lubsm_sdk \
70+ -lpthread \
71+ -Wl,-rpath,"${UBSM_LIB_DIR}"
72+else
73+ echo "[binary] ${BIN}"
74+fi
75+ 
76+if [[ ! -x "${BIN}" ]]; then
77+ echo "[error] flow_control_queue_test not found or not executable: ${BIN}" >&2
78+ echo " Copy it from the build machine, or set BUILD_LOCAL=1 to compile locally." >&2
79+ echo " You can also set BIN=/path/to/flow_control_queue_test." >&2
80+ exit 1
81+fi
82+ 
83+if [[ ! -x "${SHM_CREATOR}" ]]; then
84+ echo "[error] node_ubsm_shm_creator not found or not executable: ${SHM_CREATOR}" >&2
85+ echo " Set SHM_CREATOR=/path/to/node_ubsm_shm_creator and retry." >&2
86+ exit 1
87+fi
88+ 
89+run_once()
90+{
91+ local case_name=$1
92+ local capacity=$2
93+ local perf_messages=$3
94+ local suffix=$4
95+ local sender_shm="${SENDER_SHM}_${suffix}"
96+ local receiver_shm="${RECEIVER_SHM}_${suffix}"
97+ 
98+ CREATED_SHMS+=("${SENDER_HOST}:${sender_shm}" "${RECEIVER_HOST}:${receiver_shm}")
99+ 
100+ echo "[shm] create ${SENDER_HOST}:${sender_shm} ${RECEIVER_HOST}:${receiver_shm}"
101+ "${SHM_CREATOR}" delete "${SENDER_HOST}" "${sender_shm}" >/dev/null 2>&1 || true
102+ "${SHM_CREATOR}" delete "${RECEIVER_HOST}" "${receiver_shm}" >/dev/null 2>&1 || true
103+ "${SHM_CREATOR}" create "${SENDER_HOST}" "${sender_shm}"
104+ "${SHM_CREATOR}" create "${RECEIVER_HOST}" "${receiver_shm}"
105+ 
106+ echo "[run] role B case=${case_name} capacity=${capacity}"
107+ "${BIN}" --role B \
108+ -s "${sender_shm}" \
109+ -r "${receiver_shm}" \
110+ --capacity "${capacity}" \
111+ --threshold "${THRESHOLD}" \
112+ --wait "${WAIT_SECONDS}" \
113+ --log-level "${LOG_LEVEL}" &
114+ B_PID=$!
115+ 
116+ sleep 2
117+ 
118+ echo "[run] role A case=${case_name} capacity=${capacity} perf_messages=${perf_messages}"
119+ "${BIN}" --role A \
120+ -s "${sender_shm}" \
121+ -r "${receiver_shm}" \
122+ --case "${case_name}" \
123+ --capacity "${capacity}" \
124+ --threshold "${THRESHOLD}" \
125+ --perf-messages "${perf_messages}" \
126+ --wait "${WAIT_SECONDS}" \
127+ --log-level "${LOG_LEVEL}"
128+ 
129+ wait "${B_PID}"
130+ B_PID=""
131+ 
132+ "${SHM_CREATOR}" delete "${SENDER_HOST}" "${sender_shm}" >/dev/null 2>&1 || true
133+ "${SHM_CREATOR}" delete "${RECEIVER_HOST}" "${receiver_shm}" >/dev/null 2>&1 || true
134+}
135+ 
136+if [[ "${RUN_MATRIX}" == "1" ]]; then
137+ read -r -a capacities <<< "${CAPACITY_MATRIX}"
138+ read -r -a perf_messages_list <<< "${PERF_MESSAGES_MATRIX}"
139+ if [[ "${#capacities[@]}" -ne "${#perf_messages_list[@]}" ]]; then
140+ echo "[error] CAPACITY_MATRIX and PERF_MESSAGES_MATRIX must have the same item count" >&2
141+ exit 1
142+ fi
143+ 
144+ for idx in "${!capacities[@]}"; do
145+ cap="${capacities[$idx]}"
146+ msgs="${perf_messages_list[$idx]}"
147+ if [[ "${cap}" -ge 2048 ]]; then
148+ run_once "hotupdate" "${cap}" "${msgs}" "matrix_${idx}"
149+ else
150+ run_once "all" "${cap}" "${msgs}" "matrix_${idx}"
151+ fi
152+ done
153+else
154+ run_once "${CASE_NAME}" "${CAPACITY}" "${PERF_MESSAGES}" "single"
155+fi
156+ 
157+echo "[done] flow-control validation passed"
@@ -0,0 +1,186 @@
1+#!/usr/bin/env bash
2+ 
3+set -euo pipefail
4+ 
5+ROOT_DIR=$(cd "$(dirname "$0")/../.." && pwd)
6+SAMPLE_DIR="${ROOT_DIR}/sample_code/ub_comm_queue"
7+SRC="${SAMPLE_DIR}/flow_control_queue_test.cpp"
8+ 
9+MODE="${MODE:-help}"
10+BIN="${BIN:-${SAMPLE_DIR}/flow_control_queue_test}"
11+OUT="${OUT:-${BIN}}"
12+SHM_CREATOR="${SHM_CREATOR:-./node_ubsm_shm_creator}"
13+ 
14+TEST_ID="${TEST_ID:-manual}"
15+SENDER_SHM="${SENDER_SHM:-flow_sender_${TEST_ID}}"
16+RECEIVER_SHM="${RECEIVER_SHM:-flow_receiver_${TEST_ID}}"
17+SENDER_HOST="${SENDER_HOST:-slot1}"
18+RECEIVER_HOST="${RECEIVER_HOST:-slot2}"
19+ 
20+CASE_NAME="${CASE_NAME:-all}"
21+CAPACITY="${CAPACITY:-64}"
22+THRESHOLD="${THRESHOLD:-50}"
23+PERF_MESSAGES="${PERF_MESSAGES:-20000}"
24+WAIT_SECONDS="${WAIT_SECONDS:-20}"
25+LOG_LEVEL="${LOG_LEVEL:-3}"
26+ 
27+CXX="${CXX:-g++}"
28+CXXFLAGS_EXTRA="${CXXFLAGS_EXTRA:-}"
29+LDFLAGS_EXTRA="${LDFLAGS_EXTRA:-}"
30+COMM_INCLUDE="${COMM_INCLUDE:-${ROOT_DIR}/include}"
31+COMM_SRC_INCLUDE="${COMM_SRC_INCLUDE:-${ROOT_DIR}/src/ub_comm_queue}"
32+UBSM_INCLUDE="${UBSM_INCLUDE:-/usr/local/ubs_mem/include}"
33+COMM_LIB_DIR="${COMM_LIB_DIR:-/usr/lib64}"
34+UBSM_LIB_DIR="${UBSM_LIB_DIR:-/usr/local/ubs_mem/lib}"
35+ 
36+usage()
37+{
38+ cat <<EOF
39+Two-node ub_comm_queue flow-control validation.
40+ 
41+This script is meant to be copied to both nodes together with flow_control_queue_test.
42+It does not ssh to the other node.
43+ 
44+Common environment:
45+ TEST_ID=${TEST_ID}
46+ SENDER_HOST=${SENDER_HOST}
47+ RECEIVER_HOST=${RECEIVER_HOST}
48+ SENDER_SHM=${SENDER_SHM}
49+ RECEIVER_SHM=${RECEIVER_SHM}
50+ BIN=${BIN}
51+ SHM_CREATOR=${SHM_CREATOR}
52+ 
53+Modes:
54+ MODE=build Compile flow_control_queue_test on a build machine.
55+ MODE=create Create slot1/slot2 exported shared memory.
56+ MODE=run-b Run role B. Execute this on ${RECEIVER_HOST}.
57+ MODE=run-a Run role A. Execute this on ${SENDER_HOST} after role B is ready.
58+ MODE=cleanup Delete slot1/slot2 exported shared memory.
59+ 
60+Build example on build machine:
61+ MODE=build OUT=/tmp/flow_control_queue_test bash $0
62+ 
63+Copy example:
64+ scp /tmp/flow_control_queue_test ${SENDER_HOST}:/path/to/flow_control_queue_test
65+ scp /tmp/flow_control_queue_test ${RECEIVER_HOST}:/path/to/flow_control_queue_test
66+ scp $0 ${SENDER_HOST}:/path/to/
67+ scp $0 ${RECEIVER_HOST}:/path/to/
68+ 
69+Two-node run example:
70+ # On either node that can run node_ubsm_shm_creator:
71+ TEST_ID=t001 MODE=create SHM_CREATOR=./node_ubsm_shm_creator bash $0
72+ 
73+ # On ${RECEIVER_HOST}:
74+ TEST_ID=t001 MODE=run-b BIN=/path/to/flow_control_queue_test bash $0
75+ 
76+ # On ${SENDER_HOST}:
77+ TEST_ID=t001 MODE=run-a BIN=/path/to/flow_control_queue_test CASE_NAME=all bash $0
78+ 
79+ # Cleanup:
80+ TEST_ID=t001 MODE=cleanup SHM_CREATOR=./node_ubsm_shm_creator bash $0
81+ 
82+Hot-update interval case:
83+ TEST_ID=t002 MODE=create CAPACITY=2048 bash $0
84+ TEST_ID=t002 MODE=run-b CAPACITY=2048 BIN=/path/to/flow_control_queue_test bash $0
85+ TEST_ID=t002 MODE=run-a CAPACITY=2048 CASE_NAME=hotupdate BIN=/path/to/flow_control_queue_test bash $0
86+ TEST_ID=t002 MODE=cleanup bash $0
87+EOF
88+}
89+ 
90+require_binary()
91+{
92+ if [[ ! -x "${BIN}" ]]; then
93+ echo "[error] flow_control_queue_test not found or not executable: ${BIN}" >&2
94+ echo " Build it with MODE=build, copy it to this node, or set BIN=/path/to/binary." >&2
95+ exit 1
96+ fi
97+}
98+ 
99+require_creator()
100+{
101+ if [[ ! -x "${SHM_CREATOR}" ]]; then
102+ echo "[error] node_ubsm_shm_creator not found or not executable: ${SHM_CREATOR}" >&2
103+ echo " Set SHM_CREATOR=/path/to/node_ubsm_shm_creator." >&2
104+ exit 1
105+ fi
106+}
107+ 
108+build_binary()
109+{
110+ mkdir -p "$(dirname "${OUT}")"
111+ echo "[build] ${OUT}"
112+ "${CXX}" -O2 -g -std=c++17 ${CXXFLAGS_EXTRA} -o "${OUT}" "${SRC}" \
113+ -I"${COMM_INCLUDE}" \
114+ -I"${COMM_SRC_INCLUDE}" \
115+ -I"${UBSM_INCLUDE}" \
116+ -L"${COMM_LIB_DIR}" \
117+ -L"${UBSM_LIB_DIR}" \
118+ ${LDFLAGS_EXTRA} \
119+ -lubturbo_tdsql \
120+ -lubsm_sdk \
121+ -lpthread \
122+ -Wl,-rpath,"${UBSM_LIB_DIR}"
123+}
124+ 
125+create_shm()
126+{
127+ require_creator
128+ echo "[shm] recreate ${SENDER_HOST}:${SENDER_SHM}"
129+ "${SHM_CREATOR}" delete "${SENDER_HOST}" "${SENDER_SHM}" >/dev/null 2>&1 || true
130+ "${SHM_CREATOR}" create "${SENDER_HOST}" "${SENDER_SHM}"
131+ 
132+ echo "[shm] recreate ${RECEIVER_HOST}:${RECEIVER_SHM}"
133+ "${SHM_CREATOR}" delete "${RECEIVER_HOST}" "${RECEIVER_SHM}" >/dev/null 2>&1 || true
134+ "${SHM_CREATOR}" create "${RECEIVER_HOST}" "${RECEIVER_SHM}"
135+}
136+ 
137+cleanup_shm()
138+{
139+ require_creator
140+ echo "[shm] delete ${SENDER_HOST}:${SENDER_SHM}"
141+ "${SHM_CREATOR}" delete "${SENDER_HOST}" "${SENDER_SHM}" >/dev/null 2>&1 || true
142+ echo "[shm] delete ${RECEIVER_HOST}:${RECEIVER_SHM}"
143+ "${SHM_CREATOR}" delete "${RECEIVER_HOST}" "${RECEIVER_SHM}" >/dev/null 2>&1 || true
144+}
145+ 
146+run_role()
147+{
148+ local role=$1
149+ require_binary
150+ echo "[run] role=${role} sender_shm=${SENDER_SHM} receiver_shm=${RECEIVER_SHM} case=${CASE_NAME} capacity=${CAPACITY}"
151+ "${BIN}" --role "${role}" \
152+ -s "${SENDER_SHM}" \
153+ -r "${RECEIVER_SHM}" \
154+ --case "${CASE_NAME}" \
155+ --capacity "${CAPACITY}" \
156+ --threshold "${THRESHOLD}" \
157+ --perf-messages "${PERF_MESSAGES}" \
158+ --wait "${WAIT_SECONDS}" \
159+ --log-level "${LOG_LEVEL}"
160+}
161+ 
162+case "${MODE}" in
163+ build)
164+ build_binary
165+ ;;
166+ create)
167+ create_shm
168+ ;;
169+ run-b)
170+ run_role B
171+ ;;
172+ run-a)
173+ run_role A
174+ ;;
175+ cleanup)
176+ cleanup_shm
177+ ;;
178+ help|-h|--help)
179+ usage
180+ ;;
181+ *)
182+ echo "[error] unknown MODE=${MODE}" >&2
183+ usage
184+ exit 1
185+ ;;
186+esac
Asample_code/ub_comm_queue/test_ping.cpp+401-0File content is under review, please try again later
@@ -0,0 +1,279 @@
1+ 
2+#include <stdio.h>
3+#include <stdlib.h>
4+#include <string.h>
5+#include <unistd.h>
6+#include <atomic>
7+#include <chrono>
8+#include <thread>
9+#include <vector>
10+#include <getopt.h>
11+#include <algorithm>
12+#include <numeric>
13+#include <mutex>
14+#include <cinttypes>
15+#include <errno.h>
16+#include <stdio.h>
17+#include <stdlib.h>
18+#include <string.h>
19+#include <sys/ipc.h>
20+#include <sys/mman.h>
21+#include <sys/shm.h>
22+#include <sys/types.h>
23+#include <unistd.h>
24+#include <algorithm>
25+#include <atomic>
26+#include <chrono>
27+#include <cstdlib>
28+#include <cstring>
29+#include <iostream>
30+#include <mutex>
31+#include <set>
32+#include <thread>
33+#include <vector>
34+#include <fcntl.h>
35+#include <sys/stat.h>
36+#include <cstddef>
37+#include <future>
38+ 
39+#include "ub_dist_comm_queue.h"
40+#include "ubs_mem.h"
41+#include "ubs_mem_def.h"
42+ 
43+using namespace std::chrono_literals;
44+ 
45+enum MsgType : uint8_t {
46+ TYPE_PING = 100,
47+ TYPE_PONG = 101
48+};
49+ 
50+int my_stdout_logger(int level, const char *file, const char *func, uint32_t line, const char *message)
51+{
52+ const char *level_str = "UNKNOWN";
53+ switch (level) {
54+ case 0:
55+ level_str = "DEBUG";
56+ break;
57+ case 1:
58+ level_str = "INFO";
59+ break;
60+ case 2:
61+ level_str = "WARN";
62+ break;
63+ case 3:
64+ level_str = "ERROR";
65+ break;
66+ case 4:
67+ level_str = "CRITICAL";
68+ break;
69+ default:
70+ break;
71+ }
72+ 
73+ time_t now = time(0);
74+ char *time_str = ctime(&now);
75+ time_str[strlen(time_str) - 1] = '\0';
76+ 
77+ fprintf(stdout, "[%s] [%s:%u] [%s] %s\n", time_str, file, line, level_str, message);
78+ 
79+ return 0;
80+}
81+ 
82+static const size_t RING_CAPACITY = 1024;
83+static const size_t SLOT_SIZE = 1024;
84+static const uint32_t MIN_BODY_LENGTH = 48;
85+ 
86+static unsigned long g_shm_size_mb = 128;
87+static uint64_t NodeA = 0;
88+static uint64_t NodeB = 1;
89+// 改为可修改的全局变量
90+static char kSenderShmName[64] = "shm_node0_export";
91+static char kReceiverShmName[64] = "shm_node1_export";
92+ 
93+static uint64_t g_expect = 0;
94+ 
95+#pragma pack(push, 1)
96+struct PingPongMsg {
97+ uint32_t msg_id;
98+ int64_t A_send_time;
99+ int64_t B_recv_time;
100+ int64_t B_send_time;
101+ int64_t A_recv_time;
102+ char padding[12];
103+};
104+#pragma pack(pop)
105+static_assert(sizeof(PingPongMsg) == MIN_BODY_LENGTH, "PingPongMsg must be 48 bytes");
106+ 
107+static inline int64_t get_ns() {
108+ return (int64_t)std::chrono::duration_cast<std::chrono::nanoseconds>(
109+ std::chrono::steady_clock::now().time_since_epoch()).count();
110+}
111+ 
112+static std::atomic<uint64_t> g_ping_recv{0};
113+static std::atomic<uint64_t> g_pong_send{0};
114+static std::atomic<int64_t> g_b_process_sum{0};
115+ 
116+static void on_ping_msg(const message_t *msg, void *ctx) {
117+ const int64_t t_recv = get_ns();
118+ if (msg->header.msg_type != TYPE_PING || msg->header.body_length != MIN_BODY_LENGTH) {
119+ return;
120+ }
121+ 
122+ PingPongMsg local;
123+ memcpy(&local, msg->body, sizeof(local));
124+ 
125+ local.B_recv_time = t_recv;
126+ local.B_send_time = get_ns();
127+ 
128+ message_t pong{};
129+ pong.header.dest_node_id = NodeA;
130+ pong.header.src_node_id = NodeB;
131+ pong.header.msg_type = TYPE_PONG;
132+ pong.header.priority = 1;
133+ pong.header.body_length = MIN_BODY_LENGTH;
134+ pong.body = (char*)&local;
135+ 
136+ ub_shm_comm_t* handlep = (ub_shm_comm_t*)ctx;
137+ 
138+ for (;;) {
139+ int ret = ub_comm_queue_send(handlep, &pong);
140+ if (ret >= 0) break;
141+#if defined(__aarch64__)
142+ asm volatile("yield" ::: "memory");
143+#endif
144+ }
145+ 
146+ g_ping_recv.fetch_add(1, std::memory_order_relaxed);
147+ g_pong_send.fetch_add(1, std::memory_order_relaxed);
148+ g_b_process_sum.fetch_add(local.B_send_time - local.B_recv_time, std::memory_order_relaxed);
149+}
150+ 
151+static int init_ub_shm() {
152+ ubsmem_options_t opts{};
153+ int ret = ubsmem_init_attributes(&opts);
154+ if (ret != UBSM_OK) {
155+ fprintf(stderr, "Failed to initialize ubsmem attributes!\n");
156+ return -1;
157+ }
158+ ret = ubsmem_initialize(&opts);
159+ if (ret != UBSM_OK) {
160+ fprintf(stderr, "Failed to initialize ubsmem!\n");
161+ return -1;
162+ }
163+ ubsmem_regions_t regions = {0};
164+ ret = ubsmem_lookup_regions(&regions);
165+ if (ret != UBSM_OK) {
166+ fprintf(stderr, "Failed to look up node information!\n");
167+ return -1;
168+ }
169+ return 0;
170+}
171+ 
172+static int map_ub_shm(const char *shm_name, void *&addr) {
173+ const unsigned long length = g_shm_size_mb * 1024UL * 1024UL;
174+ int ret = ubsmem_shmem_map(nullptr, length, PROT_READ | PROT_WRITE, MAP_SHARED, shm_name, 0, &addr);
175+ if (ret != 0) {
176+ fprintf(stderr, "Failed to map shared memory '%s'! ret=%d\n", shm_name, ret);
177+ return -1;
178+ }
179+ fprintf(stdout, "Mapped '%s' at %p\n", shm_name, addr);
180+ return 0;
181+}
182+ 
183+// 新增:打印帮助信息(包含shm参数)
184+static void print_help(const char* prog) {
185+ printf("Usage: %s [-n expect_count(0=run forever)] [-s sender_shm] [-r receiver_shm] [-h]\n", prog);
186+ printf(" -n: expect pong count (0=forever, default: 0)\n");
187+ printf(" -s: sender shared memory name (default: shm_node0_export)\n");
188+ printf(" -r: receiver shared memory name (default: shm_node1_export)\n");
189+ printf(" -h: show help\n");
190+}
191+ 
192+int main(int argc, char** argv) {
193+ int opt;
194+ // 新增:解析 -s -r 参数
195+ while ((opt = getopt(argc, argv, "n:s:r:h")) != -1) {
196+ switch (opt) {
197+ case 'n': g_expect = strtoull(optarg, nullptr, 10); break;
198+ case 's': strncpy(kSenderShmName, optarg, sizeof(kSenderShmName)-1); break;
199+ case 'r': strncpy(kReceiverShmName, optarg, sizeof(kReceiverShmName)-1); break;
200+ case 'h': print_help(argv[0]); return 0;
201+ default: print_help(argv[0]); return -1;
202+ }
203+ }
204+ ub_atomic_set_log_level(LOG_LEVEL_ERROR);
205+ ub_atomic_register_log_func(my_stdout_logger);
206+ 
207+ printf("===== B Node (Ponger) ===== expect=%" PRIu64 " (0=forever)\n", g_expect);
208+ printf("sender_shm=%s receiver_shm=%s\n", kSenderShmName, kReceiverShmName);
209+ 
210+ if (init_ub_shm() != 0) return -1;
211+ 
212+ void *sender_shm_base = nullptr;
213+ if (map_ub_shm(kSenderShmName, sender_shm_base) != 0) return -1;
214+ 
215+ void *receiver_shm_base = nullptr;
216+ if (map_ub_shm(kReceiverShmName, receiver_shm_base) != 0) return -1;
217+ 
218+ ub_shm_comm_t handle = nullptr;
219+ const size_t init_size = 1024 * 1024;
220+ const size_t ring_size = 1900800;
221+ 
222+ void* init_area = sender_shm_base;
223+ void* ring_area_A = (char*)sender_shm_base + init_size;
224+ void* ring_area_B = (char*)receiver_shm_base;
225+ 
226+ ub_ring_desc_t ring_desc = {RING_CAPACITY, SLOT_SIZE, 1};
227+ ub_comm_conf_t conf = {
228+ .cpu_id = 200,
229+ .max_nodes = 2,
230+ .current_node_id = NodeB,
231+ .num_rings = 1,
232+ .ring_descs = &ring_desc
233+ };
234+ 
235+ ub_shm_area_t init_shm_area;
236+ init_shm_area.ptr = init_area;
237+ init_shm_area.size = init_size;
238+ 
239+ ub_ring_region_info_t ring_info[2];
240+ ring_info[0].node_id = NodeA;
241+ ring_info[0].region.ptr = ring_area_A;
242+ ring_info[0].region.size = ring_size;
243+ ring_info[1].node_id = NodeB;
244+ ring_info[1].region.ptr = ring_area_B;
245+ ring_info[1].region.size = ring_size;
246+ 
247+ ub_ring_region_map_t ring_map{ ring_info, 2 };
248+ 
249+ if (ub_comm_queue_init(&handle, &init_shm_area, &ring_map, &conf) != 0) {
250+ fprintf(stderr, "ub_comm_queue_init failed\n");
251+ return -1;
252+ }
253+ 
254+ ub_shm_comm_t* handlep = &handle;
255+ ub_comm_queue_register_process_func(handlep, TYPE_PING, UB_FUNC_SYNC, on_ping_msg, handlep);
256+ 
257+ printf("B ready.\n");
258+ 
259+ while (true) {
260+ if (g_expect > 0 && g_pong_send.load(std::memory_order_relaxed) >= g_expect) break;
261+ std::this_thread::sleep_for(1s);
262+ const auto cnt = g_pong_send.load(std::memory_order_relaxed);
263+ if (cnt > 0) {
264+ double avg = (double)g_b_process_sum.load(std::memory_order_relaxed) / (double)cnt;
265+ printf("[B] pong_sent=%" PRIu64 " avg_b_process(ns)=%.2f\n", cnt, avg);
266+ }
267+ }
268+ 
269+ printf("\n===== B Summary =====\n");
270+ printf("ping_recv=%" PRIu64 " pong_sent=%" PRIu64 "\n",
271+ g_ping_recv.load(), g_pong_send.load());
272+ if (g_pong_send.load() > 0) {
273+ double avg = (double)g_b_process_sum.load() / (double)g_pong_send.load();
274+ printf("avg_b_process(ns)=%.2f\n", avg);
275+ }
276+ 
277+ ub_comm_queue_deinit(&handle);
278+ return 0;
279+}
@@ -322,7 +322,7 @@ int main(int argc, char *argv[])
322 msg.body = buffer_dynamic.data(); // 使用动态缓冲区322 msg.body = buffer_dynamic.data(); // 使用动态缓冲区
323 323 
324 int send_ret = ub_comm_queue_send(&handle, &msg);324 int send_ret = ub_comm_queue_send(&handle, &msg);
325- if (send_ret != 0) {325+ if (send_ret < 0) {
326 std::cerr << " 线程 " << thread_id << " 消息 " << i << "-" << message_body_length326 std::cerr << " 线程 " << thread_id << " 消息 " << i << "-" << message_body_length
327 << "B (ID:" << id << ", Ring:" << j << ", Priority:" << (j + 1)327 << "B (ID:" << id << ", Ring:" << j << ", Priority:" << (j + 1)
328 << ") 失败: ret=" << send_ret << "\n";328 << ") 失败: ret=" << send_ret << "\n";
@@ -354,7 +354,7 @@ int main(int argc, char *argv[])
354 msg.body = buffer_dynamic.data(); // 使用动态缓冲区354 msg.body = buffer_dynamic.data(); // 使用动态缓冲区
355 355 
356 int send_ret = ub_comm_queue_send(&handle, &msg);356 int send_ret = ub_comm_queue_send(&handle, &msg);
357- if (send_ret != 0) {357+ if (send_ret < 0) {
358 std::cerr << " 线程 " << thread_id << " 消息 " << i << "-" << message_body_length << "B (ID:" << id358 std::cerr << " 线程 " << thread_id << " 消息 " << i << "-" << message_body_length << "B (ID:" << id
359 << ", Ring:0, Priority:1) 失败: ret=" << send_ret << "\n";359 << ", Ring:0, Priority:1) 失败: ret=" << send_ret << "\n";
360 }360 }
@@ -396,7 +396,7 @@ int main(int argc, char *argv[])
396 msg.body = buffer_dynamic.data(); // 使用动态缓冲区396 msg.body = buffer_dynamic.data(); // 使用动态缓冲区
397 397 
398 int send_ret = ub_comm_queue_send(&handle, &msg);398 int send_ret = ub_comm_queue_send(&handle, &msg);
399- if (send_ret != 0) {399+ if (send_ret < 0) {
400 std::cerr << " 线程 " << thread_id << " 消息 " << i << "-" << message_body_length400 std::cerr << " 线程 " << thread_id << " 消息 " << i << "-" << message_body_length
401 << "B (ID:" << id << ", Ring:" << j << ", Priority:" << (j + 1)401 << "B (ID:" << id << ", Ring:" << j << ", Priority:" << (j + 1)
402 << ") 失败: ret=" << send_ret << "\n";402 << ") 失败: ret=" << send_ret << "\n";
@@ -428,7 +428,7 @@ int main(int argc, char *argv[])
428 msg.body = buffer_dynamic.data(); // 使用动态缓冲区428 msg.body = buffer_dynamic.data(); // 使用动态缓冲区
429 429 
430 int send_ret = ub_comm_queue_send(&handle, &msg);430 int send_ret = ub_comm_queue_send(&handle, &msg);
431- if (send_ret != 0) {431+ if (send_ret < 0) {
432 std::cerr << " 线程 " << thread_id << " 消息 " << i << "-" << message_body_length << "B (ID:" << id432 std::cerr << " 线程 " << thread_id << " 消息 " << i << "-" << message_body_length << "B (ID:" << id
433 << ", Ring:0, Priority:1) 失败: ret=" << send_ret << "\n";433 << ", Ring:0, Priority:1) 失败: ret=" << send_ret << "\n";
434 }434 }
Msrc/ub_comm_queue/MPSCRingBuffer.cpp+296-26File content is under review, please try again later
Msrc/ub_comm_queue/MPSCRingBuffer.h+50-8File content is under review, please try again later
Asrc/ub_comm_queue/README.md+697-0File content is under review, please try again later
Msrc/ub_comm_queue/UBShmTransport.cpp+152-76File content is under review, please try again later
Msrc/ub_comm_queue/UBShmTransport.h+10-5File content is under review, please try again later