[swift-users] Recommendation for thread-safe dictionary
Evan Maloney
emaloney at gilt.com
Thu Dec 10 12:56:28 CST 2015
>> 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.
Speaking of which, the CleanroomConcurrency project for Swift provides a ReadWriteCoordinator that provides similar functionality using a Grand Central Dispatch feature:
https://github.com/emaloney/CleanroomConcurrency/tree/master/Code#readwritecoordinator <https://github.com/emaloney/CleanroomConcurrency/tree/master/Code#readwritecoordinator>
The flip side of the threadsafe dictionary is the thread-local dictionary associated with each NSThread which can be used in a Swifty fashion with:
https://github.com/emaloney/CleanroomConcurrency/tree/master/Code#threadlocalvalue <https://github.com/emaloney/CleanroomConcurrency/tree/master/Code#threadlocalvalue>
Disclosure: This open-source code is provided courtesy of my employer, Gilt Groupe, and ships in our "Gilt on TV" app for the new Apple TV.
> On Dec 10, 2015, at 12:28 PM, 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.
>
> —Jens
>
> * 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
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151210/0ad415f3/attachment.html>
More information about the swift-users
mailing list