Friday, February 6, 2015

Locks, Thread Safety, and Swift

Mike Ash:

Swift requires variables to be initialized before they’re used. pthread_mutex_init doesn’t use the value of the variable passed in, it just overwrites it, but Swift doesn’t know that and so it produces an error. To satisfy the compiler, the variable needs to be initialized with something, but that’s harder than it looks.


Getting data out of the block is a bit less pleasant, unfortunately. While @synchronized lets you return from within, that doesn’t work with with. Instead, you have to use a var and assign to it within the block[…]


Swift has no language facilities for thread synchronization, but this deficiency is more than made up for the wealth of locking APIs available in Apple’s frameworks. GCD and dispatch_queue_t are still a masterpiece and the API works great in Swift.

1 Comment RSS · Twitter

[…] Locks, Thread Safety, and Swift, OSSpinLock Is Unsafe, […]

Leave a Comment