Locks, Thread Safety, and Swift
Swift requires variables to be initialized before they’re used.
pthread_mutex_initdoesn’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
@synchronizedlets youreturnfrom within, that doesn’t work withwith. Instead, you have to use avarand 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_tare still a masterpiece and the API works great in Swift.