Modern Concurrency: Getting Started, Episode 4: Asynchronous Sequences | Kodeco

Learn how to define async properties and subscripts and how to iterate over built-in and custom async sequences.


This is a companion discussion topic for the original entry at https://www.kodeco.com/28434449-modern-concurrency-getting-started/lessons/4

For some reason the task is not getting canceled, I even run your “final” project

1 Like

I think, as Macs get faster, you need to increase the amount of work for the task. I added a few 0s to the named task’s sum, and it doesn’t finish.

1 Like

Neither mine, but it also doesn’t print “Task cancelled”

I noticed that if I add the zeros to the unnamed task instead, the named task finishes but the unnamed doesn’t.

Shouldn’t the named task only start after the unnamed task finishes?

1 Like

“Task cancelled” would only appear if the task.cancel() executed before the Task closure starts to run.

If you wait long enough, the unnamed task with lots of zeros does finish.

The statement that the named task starts after the unnamed task finishes assumes there are only 2 threads, and that the main thread is reserved for the main actor. But it’s possible for the system to use the main thread for other work, if nothing is happening on the main actor. Or, on a Mac, there are more than 2 processors, so there are more than 2 threads.

Ran into the same issue as well. I tried forcing both tasks to run on the main thread and now task cancellation works as expected since the second task has to wait for the first task to finish, thanks @audrey for the explanation.

Task { @MainActor in
  print("\nDoing some work on an unnamed task")
    
  let sum = (1...10000000).reduce(0, +)
  print("Unnamed task done: 1 + 2 + 3 ... 100000 = \(sum)")
}
print("Doing some work on the main queue")
print("Doing more work on the main queue")

// This task runs after previous task finishes
let task = Task { @MainActor in
  print("\nDoing some work on a named task")
...
1 Like