Locks, Thread Safety, and Swift
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 youreturn
from within, that doesn’t work withwith
. Instead, you have to use avar
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.