Are the types in Swift Collections safe for concurrency?

I added a Deque to a final class. Then I wondered if that collection is concurrency safe, because I think there’s a chance that the downstream could take an element at the same time that the upstream wants to add an element. I tried replacing the class with an actor, but I got nonisolated warnings on some methods (matching a protocol). Is there some quick-fix I can put around the element-insertion and element-removal calls?

It would be nice if you could provide a short code snippet of what you are trying to achieve.

But if I understand the question correctly:

As far as I know Deque is not thread safe by itself in terms of that it uses locks or some other mechanism.

But, if you are developing in Swift 6 you should be safe in general as you would get a compiler error if you are trying to do something that is not safe.

None of the collection types in the standard library or swift-collections are safe for concurrent mutation, and generally, data structures designed with that in mind will have a rather different set of tradeoffs than general-purpose single-threaded collections.

If you need a queue where one task produces elements and another task consumes them, the easiest way is to wrap an ordinary queue in an actor or a mutex. For maximum performance you’ll want to find or roll your own lockless data structure, though.

3 Likes

I wrote the original message before going to bed. Right after I woke up, I realized that I could wrap only the deque within an actor. Need to actually try it….

2 Likes

Remember to beware of things like “I get the count, then it changes, then I do the thing based on the count I was going to do”. Something similar to Mutex’s API where it takes a closure and passes the protected state to it may help avoid that.

1 Like