usingExecutor<T> function

T usingExecutor<T>(
  1. T computation(
    1. Executor executor
    ), {
  2. ForwardType type = ForwardType.MNN_FORWARD_CPU,
  3. BackendConfig? config,
  4. int? numThreads,
})

Execute a computation using an executor

TODO: support this NOTE: DO NOT USE!!!

Note: remember to dispose the module in computation

NOTE: Our implementation uses attach to attach a native object to a Dart object, which means in most cases, native objects will be disposed automatically when Dart objects are garbage collected. However, when they will be disposed is not guaranteed, if they are freed before the lazy computation is executed, a use-after-free may occur.

  • computation The computation to execute, which takes an executor as input and returns a result

  • type The forward type of the executor, default is MNN_FORWARD_CPU

  • config The backend config of the executor, default is null

  • numThreads The number of threads to use for the executor, default is the number of processors

return the result of the computation

Implementation

T usingExecutor<T>(
  T Function(Executor executor) computation, {
  ForwardType type = ForwardType.MNN_FORWARD_CPU,
  BackendConfig? config,
  int? numThreads,
}) {
  config ??= BackendConfig.create();
  numThreads ??= Platform.numberOfProcessors;
  // var isAsync = false;
  final executor = Executor.create(type, config, numThreads);
  executor.lazyMode = LazyMode.LAZY_FULL;
  final scope = ExecutorScope.create(executor);

  try {
    final result = computation(executor);
    if (result is Future) {
      // isAsync = true;
      return result.whenComplete(scope.dispose) as T;
    }
    return result;
  } finally {
    scope.dispose();
  }
}