[swift-users] Recommendation for thread-safe dictionary

Dmitri Gribenko gribozavr at gmail.com
Thu Dec 10 11:44:34 CST 2015


On Thu, Dec 10, 2015 at 9:24 AM, Pelaia II, Tom via swift-users <
swift-users at swift.org> wrote:

> /* provide subscript accessors */
> subscript(key: KeyType) -> ValueType? {
> get {
> var value : ValueType?
> dispatch_sync(self.queue) { () -> Void in
> value = self.internalDictionary[key]
> }
> return value
> }
>
> set {
> setValue(newValue, forKey: key)
> }
> }
>

Please don't do this, unless you have a very special use case.  This is
inherently racy on high level, even though it is safe in the language.
Consider two threads operating on a shared ConcurrentDictionary<Int, Int>:

d[42] += 1

Here's what the code compiles into:

var tmp = d.subscript_get(42)
tmp += 1
d.subscript_set(42, tmp)

The 'get' and 'set' operations are atomic, but the whole sequence isn't.
The results of operations that other threads execute during "tmp += 1" will
be overwritten by the following 'subscript_set'.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151210/739526a7/attachment.html>


More information about the swift-users mailing list