Recommendation for thread-safe dictionary

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

ยทยทยท

On Thu, Dec 10, 2015 at 9:24 AM, Pelaia II, Tom via swift-users < swift-users@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)
}
}

--
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@gmail.com>*/