Skip to content

内存管理与所有权

OnePath 的内存模型简单且一致:谁创建,谁销毁;你拿到的接收数据,归你所有,用完显式释放。 本页给出全部规则与配对表。

基本原则

  1. create / destroy 配对:所有通过 onepath_*_createonepath_declare_*onepath_open* 创建的资源,必须通过对应的 onepath_*_destroy / onepath_close 销毁。
  2. 你拿到的就是你的:回调中收到的 onepath_sample_t *onepath_request_t *已深拷贝、归用户所有。可自由保存、传递给其他线程;用完后须调用对应的 release 函数释放。
  3. 通道接收的数据:通过 onepath_reply_recv / onepath_reply_try_recv / onepath_sample_recv / onepath_sample_try_recv 获取的数据,使用完毕后必须调用对应的 release 函数释放。
  4. 字符串参数随用随弃:传入 API 的字符串参数(key、endpoint 等)在函数返回后可立即释放,库会在需要时创建内部拷贝。
  5. 配置不被消费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_recvonepath_sample_release
onepath_request_t应答回调onepath_request_release(reply 后或不再回复时)
onepath_reply_t查询回复通道(onepath_reply_recv / _try_recvonepath_reply_release

资源销毁顺序

关闭会话前,先销毁会话上的所有子资源。建议顺序:

1. 销毁发布者、订阅者、responder、requester、存活令牌等子资源
2. 销毁接收通道(sample_rx、reply_rx)
3. 销毁共享内存池(仅 full)
4. 关闭会话(onepath_close)

创建 / 销毁配对表

创建函数销毁函数
onepath_open / onepath_open_*onepath_close
onepath_config_newonepath_config_destroy
onepath_declare_publisheronepath_publisher_destroy
onepath_subscribe / onepath_subscribe_pullonepath_subscriber_destroy
onepath_subscribe_pull(rx 参数)onepath_sample_rx_destroy
onepath_declare_responderonepath_responder_destroy
应答回调中的 queryonepath_request_release
订阅回调 / pull 通道中的 sampleonepath_sample_release
onepath_declare_requesteronepath_requester_destroy
onepath_liveliness_declareonepath_liveliness_undeclare
onepath_get / onepath_requester_get / onepath_liveliness_get(rx 参数)onepath_reply_rx_destroy
回复通道中的 replyonepath_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_startonepath_topology_agent_stoponepath_close 亦自动停止)
onepath_topology_local(out 参数)onepath_topology_local_free
onepath_topology_snapshot(out 参数)onepath_topology_graph_free

后台订阅是个例外

onepath_subscribe_background 不返回句柄,其生命周期与会话绑定,会话关闭时自动终止,无需手动销毁。

便捷封装(三模存储 / 计算多模冗余 XMR)也遵循同样的 create / destroy 配对,详见各自专题页与 API 手册

OnePath™ 以预构建库形式交付,运行时零外部依赖。