---页首---

Napi::ThreadSafeFunction::New 第三个参数说明及使用场景

第三个参数 Resource Name 的使用

示例: "CaptureGuardSync" 的作用

  Napi::ThreadSafeFunction::New(
      env,
      callback,
      "CaptureGuardSync",  // ← Resource name
      0, // 队列大小,0 = 无限制;> 0 (固定大小),队列满时NonBlockingCall返回napi_queue_full
      1 // 线程计数
  );

用途 1: Node.js 异步资源跟踪

  Async Hooks API 可以追踪异步资源:

  // Node.js 代码
  const async_hooks = require('async_hooks');

  async_hooks.createHook({
      init(asyncId, type, triggerAsyncId, resource) {
          if (type === 'JSFUNCTION') {
              console.log('Resource:', resource.constructor.name);
              // 输出: Resource: CaptureGuardSync
          }
      }
  }).enable();

用途 2: 性能分析和调试

  当使用 Node.js 的性能分析工具时:

  node --prof app.js
  node --prof-process isolate-*.log

  输出中会显示:
  Statistical profiling result from isolate-*.log:
     ticks  total  nonlib   name
       42    5.2%    5.2%  CaptureGuardSync  ← 可以看到这个名字
       ...

用途 3: Chrome DevTools 性能面板

  当在 Chrome DevTools 中查看 Node.js 应用性能时:

  Performance Timeline:
    ├─ Main Thread
    │   ├─ JavaScript
    │   ├─ CaptureGuardSync (TSFN)  ← 显示在时间线上
    │   └─ Other Tasks

用途 4: 调试日志和错误追踪

  如果 ThreadSafeFunction 出现问题,Node.js 内部错误消息会包含这个名字:

  Error: Could not call ThreadSafeFunction CaptureGuardSync
      at Object.module.exports.tryAction (...)

  实际示例:多个 ThreadSafeFunction

  // 在复杂应用中可能有多个 TSFN
  auto tsfn1 = Napi::ThreadSafeFunction::New(env, cb, "CaptureGuard", 0, 1);
  auto tsfn2 = Napi::ThreadSafeFunction::New(env, cb, "AudioProcessor", 0, 1);
  auto tsfn3 = Napi::ThreadSafeFunction::New(env, cb, "VideoEncoder", 0, 1);

  // 在性能分析中可以区分它们:
  // CaptureGuard: 10ms (5%)
  // AudioProcessor: 50ms (25%)
  // VideoEncoder: 100ms (50%)

最佳实践

  // ❌ 不好:没有语义
  Napi::ThreadSafeFunction::New(env, cb, "tsfn", 0, 1);

  // ❌ 不好:太笼统
  Napi::ThreadSafeFunction::New(env, cb, "callback", 0, 1);

  // ✅ 好:清楚说明用途
  Napi::ThreadSafeFunction::New(env, cb, "CaptureGuardSync", 0, 1);
  Napi::ThreadSafeFunction::New(env, cb, "DatabaseQueryCallback", 0, 1);
  Napi::ThreadSafeFunction::New(env, cb, "ImageProcessingResult", 0, 1);

参考资料

posted @ 2026-09-10 11:26  20190311  阅读(6)  评论(0)    收藏  举报
---页脚---