[swift-users] Recommendation for thread-safe dictionary
daniel.j.stenmark at gmail.com
Thu Dec 10 12:17:49 CST 2015
+1. I learned this the hard way, once upon a time. For code that is primarily CPU bound (like dictionary reads/writes), opt for using your objects in a thread-safe way rather than creating thread-safe objects. Either make sure the callers wrap each access around a mutex/semaphore lock, or (if you’re working in OSX/iOS) ensure that each access is dispatched onto the same serial Grand Central Dispatch queue.
> On Dec 10, 2015, at 9:28 AM, Jens Alfke via swift-users <swift-users at swift.org> wrote:
>> 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.
> * which I guess you’ll have to implement using C calls to pthreads, since the Swift concurrency library isn’t ready yet
> swift-users mailing list
> swift-users at swift.org
More information about the swift-users