Tony Lin
Tony Lin

Reputation: 942

Why would threads being used up for non-main queues?

http://devstreaming.apple.com/videos/wwdc/2015/718b7aw9tq/718/718_hd_building_responsive_and_efficient_apps_with_gcd.mp4

enter image description here

at 35:43.

since all the threads in the thread pool is being used up by the concurrent queue. The dead lock happens because the main queue won't have any more available thread to run the task.

I remember that the main queue has a dedicated main thread ( or thread pool???) to make sure the main queue to run smoothly without problem.

Which part am I interpreting wrong?

Upvotes: 1

Views: 73

Answers (1)

Paulw11
Paulw11

Reputation: 114836

To clarify, tasks dispatched on the main queue will always execute on the main thread, but the main thread is not dedicated to the main queue. A task dispatched on another queue can use any available thread, including the main thread.

In the example shown in the slide, the main thread is performing the loop, submitting asynchronous tasks. Inside the dispatch_async is a synchronous block that adds the work to the queue. Once available threads are exhausted, this will block until a thread is available; so the main thread is now blocked.

However, each thread is dispatching synchronous work back to the main queue (which requires the main thread), so they will block waiting for the main thread. Since there is no pre-emption, the main thread cannot be "re-tasked" to perform the dispatch_sync, and you have a deadlock condition.

In summary:

  • The two queues are mutually blocking each other (hold and wait)
  • There is no pre-emption
  • Result: Deadlock.

Upvotes: 2

Related Questions