[swift-users] Recommendation for thread-safe dictionary

Jens Alfke jens at mooseyard.com
Thu Dec 10 11:28:48 CST 2015


> On Dec 10, 2015, at 9:18 AM, Lane Schwartz via swift-users <swift-users at swift.org> wrote:
> 
> I'm writing some code where I'd like multiple threads to be writing to a common dictionary object.
> Is there a recommended mechanism for doing this?

Wrap mutexes* around dictionary accesses. If you have a lot more reads than writes, a read/write mutex will be more efficient.

Making a thread-safe dictionary class is usually not a good idea. (This is something Java learned in between JDK 1.0 and 1.2.) It adds unavoidable overhead to every single access, and doesn’t solve the higher-level synchronization problems of the code that’s using the dictionary. Instead, use synchronization primitives in your higher-level class at the appropriate points.

—Jens

* which I guess you’ll have to implement using C calls to pthreads, since the Swift concurrency library isn’t ready yet


More information about the swift-users mailing list