3

As we all know: Task.init creates an unstructured task that runs on the current actor, Task.detachedcreates an unstructured task that’s not part of the current actor.

I understand those differences when the context of creating a new unstructured task is on the main actor or any other actor, but what about it is on a concurrent executor other than a serial executor (which means an actor). In this situation, what's the difference between Task.init and Task.detached?

A Task does have a chance to NOT run on any actor, right?

Li Fumin
  • 1,383
  • 2
  • 15
  • 31

2 Answers2

2

what's the difference between Task.init and Task.detached?

  1. Task.detached - detached tasks do not inherit task-local values

From the doc for @TaskLocal

@TaskLocal
static var traceID: TraceID?

print("traceID: \(traceID)") // traceID: nil

$traceID.withValue(1234) { // bind the value
  print("traceID: \(traceID)") // traceID: 1234
  call() // traceID: 1234

  Task { // unstructured tasks do inherit task locals by copying
    call() // traceID: 1234
  }

  Task.detached { // detached tasks do not inherit task-local values
    call() // traceID: nil
  }
}

func call() {
  print("traceID: \(traceID)") // 1234
}
  1. Task.detached - detached tasks do not inherit the parent task’s priority. You can set TaskPriority in the Task.detached call.
Jurasic
  • 1,845
  • 1
  • 23
  • 29
1

Besides differing on whether to inherit actor context in tasks created with Task.init and Task.detached, there are other differences as well:

  1. Tasks created with Task.init inherit parent task's TaskLocal values.
  2. Tasks created with Task.detached don't inherit task priority. The priority should be manually provided or medium priority is used by default.

And if the task isn't associated with any actor it is executed by concurrent executor/concurrent pool. So yes, a task might not always be associated with actor.

Soumya Mahunt
  • 2,148
  • 12
  • 30
  • Where can I learn more about the concurrent executor/pool? – rayaantaneja Mar 21 '23 at 09:17
  • 1
    @rayaantaneja WWDC videos are pretty good for beginner-level understanding, after that, you can look into the Swift proposals for actors to get to know more about design decisions. – Soumya Mahunt Mar 21 '23 at 09:31