Deadlock example
Example of deadlock in swift

  Mar 26, 2019 -   read
  ios, swift, tips

Deadlock is a situation when two or more threads are waiting on each other to be completed causing both to be locked and not able to continue.

A practical example of a deadlock is

Let’s see an example in swift.

here, the the queue is exeucting with q.async first, inside the block it calls for q.sync. So the outer block can only complete when the inner block q.sync is finished, but q.sync cannot start, because it is a sync block unless the thread is free. This results in a deadlock and the process will crash.

import Foundation

class Resource {
	
	private(set) var value: Int
	
	private let q = DispatchQueue(label: "myQueue")
	
	init(_ value: Int) {
		self.value = value
	}

	// Deadlock
	func set(_ value: Int) {
		q.async {
			print("async")
			self.q.sync {
				self.value = value
				print("sync") 	 	// outer block is waiting for this inner block to complete,
        							// inner block won't start before outer block finishes
        							// => deadlock
			}
			print("finished") // this will never be reached
		}
	}
}

let r = Resource(100)
r.set(200)

print("final value \(r.value)")

// Output
// async
// Execution Interrupted due to deadlock
Suraj Pathak
Swift Brewer