惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
aimingoo的专栏
aimingoo的专栏
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 聂微东
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
Blog — PlanetScale
Blog — PlanetScale
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
D
DataBreaches.Net
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
L
LangChain Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
F
Fortinet All Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
Recent Announcements
Recent Announcements
Jina AI
Jina AI
G
Google Developers Blog
腾讯CDC
博客园_首页
博客园 - 【当耐特】

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
[SC] Usar un ejecutor de actor personalizado
GoyesDev · 2026-04-26 · via DEV Community

Preguntas

¿En qué situaciones el executor por defecto de Swift resulta insuficiente y cuándo debería considerarse un ejecutor personalizado?

  • No se quiere usar el pool de hilos global cooperativo.
  • Se quiere usar una cola serial específica.
  • Se quiere enganchar un hilo específico.

Puede ser el caso de una biblioteca de terceros que espera recibir un DispatchQueue serial para orquestar sus operaciones.

¿Qué diferencia hay entre un SerialExecutor y un TaskExecutor, y para qué sirve cada uno?

Un SerialExecutor sirve para despachar tareas en un actor, mientras que un TaskExecutor sirve para despachar tareas en un Task.

¿Por qué es importante que el actor mantenga una referencia fuerte al ejecutor cuando se usa asUnownedSerialExecutor()?

asUnownedSerialExecutor() entrega una referencia simple a un objeto en el heap sin conteo de referencias. Por esta razón, si no se retiene la referencia, el objeto se pierde.

¿Cómo funciona el método enqueue(_:) dentro de un SerialExecutor basado en DispatchQueue?

Se despacha una tarea en la cola seria (i.e. dispatchQueue.async) que consiste en ejecutar síncronamente un UnownedJob en un SerialExecutor (i.e. unownedJob.runSynchronously(on: unownedExecutor)).

final class DispatchQueueExecutor: SerialExecutor {
  private let dispatchQueue: DispatchQueue
  init(dispatchQueue: DispatchQueue) {
    self.dispatchQueue = dispatchQueue
  }

  func enqueue(_ job: consuming ExecutorJob) {
    let unownedJob = UnownedJob(job)
    let unownedExecutor = asUnownedSerialExecutor()

    dispatchQueue.async {
      unownedJob.runSynchronously(on: unownedExecutor)
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

actor LoggingActor {
  private let executor: DispatchQueueExecutor
  nonisolated var unownedExecutor: UnownedSerialExecutor {
    executor.asUnownedSerialExecutor()
  }

  init(dispatchQueue: DispatchQueue) {
    self.executor = DispatchQueueExecutor(dispatchQueue: dispatchQueue)
  }

  func log(_ message: String) {
    print("[\(Thread.current)]: \(message)")
  }
}

Enter fullscreen mode Exit fullscreen mode

¿Qué métodos permiten configurar una preferencia de ejecutor para tareas no aisladas a un actor?

Primero hay que crear un TaskExecutor. Notar en el siguiente código cómo se conforma TaskExecutor y cómo se despacha dentro de la cola serial (i.e. dispatchQueue.async) una tarea que consiste en ejecutar síncronamente el job recibido (i.e. unownedJob.runSynchronously(on: unownedExecutor)):

final class DispatchQueueTaskExecutor: TaskExecutor {
  private let dispatchQueue: DispatchQueue
  init(dispatchQueue: DispatchQueue) {
    self.dispatchQueue = dispatchQueue
  }
  func enqueue(_ job: consuming ExecutorJob) {
    let unownedJob = UnownedJob(job)
    let unownedExecutor = asUnownedTaskExecutor()

    dispatchQueue.async {
      unownedJob.runSynchronously(on: unownedExecutor)
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Luego, al definir el Task, se le pasa el ejecutor preferido:

struct DispatchQueueTaskExecutorTests {
  @Test
  func execute() async {
    let queue = DispatchQueue(label: "com.logger.queue")

    let taskExecutor = DispatchQueueTaskExecutor(dispatchQueue: queue)

    await Task(executorPreference: taskExecutor) {
      print("Task Executor example")
    }.value

    #expect(1 == 1)
  }
}

Enter fullscreen mode Exit fullscreen mode

¿Qué métodos permiten configurar una preferencia de ejecutor para tareas aisladas a un actor?

Para ejecutar una tarea aislada a un actor se usa runSynchronously(isolatedTo:taskExecutor:) en lugar de runSynchronously(on:) como se muestra a continuación:

final class DispatchQueueTaskExecutor: TaskExecutor {
  private let dispatchQueue: DispatchQueue
  init(dispatchQueue: DispatchQueue) {
    self.dispatchQueue = dispatchQueue
  }
  func enqueue(_ job: consuming ExecutorJob) {
    let unownedJob = UnownedJob(job)
    let unownedExecutor = asUnownedTaskExecutor()

    dispatchQueue.async {
      unownedJob.runSynchronously(isolatedTo: DispatchQueueExecutor.loggingExecutor.asUnownedSerialExecutor(), taskExecutor: self.asUnownedTaskExecutor())
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Mostrar un ejemplo donde se comparta un executor entre actores

Se debe mantener una referencia al executor como si fuera un singleton (e.g. static let loggingExecutor). Luego, el actor hará referencia a ese singleton desde var unownedExecutor: UnownedSerialExecutor.

extension DispatchQueueExecutor {
  static let loggingExecutor = DispatchQueueExecutor(
    dispatchQueue: DispatchQueue(label: "com.logger.queue", qos: .utility)
  )
}

actor SharedExecutorLoggingActor {
  nonisolated var unownedExecutor: UnownedSerialExecutor {
    DispatchQueueExecutor.loggingExecutor.asUnownedSerialExecutor()
  }

  func log(_ message: String) {
    print("[\(Thread.current)] \(message)")
  }
}

Enter fullscreen mode Exit fullscreen mode


Recordar sin mirar

¿Cuál es la diferencia entre compartir un ejecutor entre múltiples actores y que cada actor tenga el suyo propio? ¿Qué implicaciones tiene esto en la concurrencia?

¿Qué restricción importante existe al combinar TaskExecutor y SerialExecutor en un mismo tipo?


Revisión y reflexión

El artículo describe los ejecutores personalizados como una "solución excepcional". ¿En qué escenarios concretos del desarrollo real estaría justificado usarlos frente al executor por defecto?

¿Qué riesgos o errores podrían surgir si se implementa incorrectamente un ejecutor personalizado, por ejemplo usando una cola concurrente donde se requiere una serial?


Bibliografía