Settings

Theme

Swift concurrency – things they don’t tell you

wojciechkulik.pl

28 points by teichmann 3 years ago · 7 comments

Reader

cvwright 3 years ago

I really enjoy working in Swift these days, and async/await has been a huge blessing.

But the whole way that Actors were rolled out leaves a funny taste.

Apple’s main illustrating example for using an Actor was to update a database. But if you try to do that, you run into exactly the same reentrancy issue described in this article!

While your Actor function is await’ing on the database, you can have another call to the same function start running, trying to write a different value to the DB. Now you have a race condition — exactly the kind of pain that Actors were supposed to save us from.

WTF Apple?!?

It would be ok if the first version was presented as a stepping stone to greater things. Instead they piss on our heads and tell us it’s raining.

  • morsch 3 years ago

    Updating databases (e.g. views) is a common thing we do using Akka actors. While a DB call is running, you store incoming updates in a local var, and once the DB update is done, you start the next DB update with the whole batch. So you never have more than one concurrent DB call, and there is no race condition. This all fits in quite well into the actor model.

    • mrkeen 3 years ago

      Actor's claim to fame is no race conditions because no shared state. Haven't you just reintroduced shared state with that approach?

      • morsch 3 years ago

        No. I've introduced state, but no shared state; the "next batch" var is local to the actor and not shared.

        Critically, the only one who updates the variable is the actor itself in its thread; it could be a plain list, and not a concurrent queue as it might be in a different multiple producer/single consumer architecture.

        PS -- I'll add that in Akka itself, the actor's mailbox, in which messages accumulate until the actor next gets allotted a thread, is exactly a kind of concurrent queue, at least in its default implementation.

pjmlp 3 years ago

It is kind of interesting to see all ecosystems that have adopted async/await to go through the same pain points as we have in .NET.

It took from .NET 4.5 up to .NET 5 (don't forget the whole .NET Core transition in the middle), to sort out the async/await across all possible workflows, and after all this, they started to consider also adding virtual threads support due to the colouring aspect of it.

rkunde 3 years ago

The article mentions thread explosion quite a bit. If that’s a concern, you should take a look at target dispatch queues. https://developer.apple.com/documentation/dispatch/dispatcho...

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection