内存管理与所有权
OnePath 的内存模型简单且一致:谁创建,谁销毁;你拿到的接收数据,归你所有,用完显式释放。 本页给出全部规则与配对表。
基本原则
- create / destroy 配对:所有通过
onepath_*_create、onepath_declare_*、onepath_open*创建的资源,必须通过对应的onepath_*_destroy/onepath_close销毁。 - 你拿到的就是你的:回调中收到的
onepath_sample_t *和onepath_request_t *均已深拷贝、归用户所有。可自由保存、传递给其他线程;用完后须调用对应的 release 函数释放。 - 通道接收的数据:通过
onepath_reply_recv/onepath_reply_try_recv/onepath_sample_recv/onepath_sample_try_recv获取的数据,使用完毕后必须调用对应的 release 函数释放。 - 字符串参数随用随弃:传入 API 的字符串参数(key、endpoint 等)在函数返回后可立即释放,库会在需要时创建内部拷贝。
- 配置不被消费:
onepath_open_with_config内部拷贝配置,调用后cfg仍有效,用完仍须自行onepath_config_destroy。
深拷贝样本与回调
订阅回调(onepath_sample_cb)与应答回调(onepath_request_cb)收到的数据是深拷贝,其生命周期独立于回调——你可以把它入队、跨线程处理,再在任意时刻释放:
c
static void on_sample(onepath_sample_t *sample, void *userdata)
{
/* sample 归你所有,可保存、可跨线程;用完必须释放 */
onepath_sample_release(sample);
}c
static void on_request(onepath_request_t *query, void *userdata)
{
/* 可同步回复,也可保存 query 后异步回复 */
onepath_request_reply_str(query, query->key, "ok");
onepath_request_release(query); /* reply 完成后释放 */
}例外:发现 / 信息回调不是深拷贝
onepath_hello_t *(scouting)与 onepath_node_id_t *(info 枚举)仅在回调执行期间有效,没有 release 函数。如需保留,必须在回调内自行拷贝。
各类接收数据的释放函数
| 数据 | 来源 | 释放函数 |
|---|---|---|
onepath_sample_t | 订阅回调、pull 通道(onepath_sample_recv / _try_recv) | onepath_sample_release |
onepath_request_t | 应答回调 | onepath_request_release(reply 后或不再回复时) |
onepath_reply_t | 查询回复通道(onepath_reply_recv / _try_recv) | onepath_reply_release |
资源销毁顺序
关闭会话前,先销毁会话上的所有子资源。建议顺序:
1. 销毁发布者、订阅者、responder、requester、存活令牌等子资源
2. 销毁接收通道(sample_rx、reply_rx)
3. 销毁共享内存池(仅 full)
4. 关闭会话(onepath_close)创建 / 销毁配对表
| 创建函数 | 销毁函数 |
|---|---|
onepath_open / onepath_open_* | onepath_close |
onepath_config_new | onepath_config_destroy |
onepath_declare_publisher | onepath_publisher_destroy |
onepath_subscribe / onepath_subscribe_pull | onepath_subscriber_destroy |
onepath_subscribe_pull(rx 参数) | onepath_sample_rx_destroy |
onepath_declare_responder | onepath_responder_destroy |
应答回调中的 query | onepath_request_release |
订阅回调 / pull 通道中的 sample | onepath_sample_release |
onepath_declare_requester | onepath_requester_destroy |
onepath_liveliness_declare | onepath_liveliness_undeclare |
onepath_get / onepath_requester_get / onepath_liveliness_get(rx 参数) | onepath_reply_rx_destroy |
回复通道中的 reply | onepath_reply_release |
onepath_shm_pool_create(仅 full) | onepath_shm_pool_destroy |
onepath_declare_advanced_publisher(仅 full) | onepath_publisher_destroy |
onepath_subscribe_advanced(仅 full) | onepath_subscriber_destroy |
onepath_topology_agent_start | onepath_topology_agent_stop(onepath_close 亦自动停止) |
onepath_topology_local(out 参数) | onepath_topology_local_free |
onepath_topology_snapshot(out 参数) | onepath_topology_graph_free |
后台订阅是个例外
onepath_subscribe_background 不返回句柄,其生命周期与会话绑定,会话关闭时自动终止,无需手动销毁。
便捷封装(三模存储 / 计算、多模冗余 XMR)也遵循同样的 create / destroy 配对,详见各自专题页与 API 手册。