Mutexes in Swift

It’s a gigantic, complicated subject.

As of March 2018, Swift 4 lacks support for threading, and there are no rumors of it coming apart from a 2016-era proposal.

Many Objective C programmers recommend emulating its @synchronized implementation, which would look like this in Swift:

Swift 4
func synchronized(_ lock: AnyObject, _ body: () throws -> T) rethrows -> T {
    defer { objc_sync_exit(lock) }
    return try body()

Sample usage:

Swift 4
synchronized(self) {
    print("This is a synchronized closure")

Gallagher prefers pthread_mutex_lock because it’s both portable and the fastest over millions of calls. See his article for the details.

I’ll stick with the above until further notice, probably prompted by a mysterious bug or performance issue.