Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
From the author of Join the Queue

Join the Queue

So, why have I been talking about blocks and Kqueue, when I said I was going to talk about Grand Central? Because, at the core, GCD is a way of joining these two features together. GCD is a mechanism for managing queues that run blocks. They can also use pure function pointers; a function pointer with a data pointer is semantically equivalent to a block, but a bit less user-friendly. GCD is event-driven. Queues run blocks in response to events. These can then add other blocks to other queues and so on.

Each queue has a priority, like a thread. Conceptually, you can think of each queue as being a lightweight thread. Under the hood, they use the pthread_workqueue family of calls to manage threads. These are (more or less undocumented) system calls added with OS X 10.6 that handle the creation of a group of threads responsible for handling events.

Work queues are fundamental to the programming model used for GCD. They are effectively FIFOs into which you push blocks. There are two kinds of queues: ones that must be run in series and ones that may be run in parallel. If you add two blocks to a queue of the first type, the one will be run and then the other. With the second type, the same may happen, or the two blocks may execute concurrently in separate threads.

This is where the pthread_workqueue_ family of calls comes in. This allows the kernel to decide the number of threads to create. By default, it will create one thread for each CPU and for each priority level. If you create workqueues with two priority levels on a quad-core computer, you will get eight threads. The story doesn't end quite there, however, because the kernel is aware of the global system load. If there are already a lot of busy threads, you may only get two. Your program will then run on one core, and other programs will run on others, reducing cache churn and context switch overhead. If, on the other hand, most of your threads are blocking waiting for I/O, then you may get some more. This extra support hasn't yet made it into the FreeBSD port, which is a shame because it's one of the nicer features of GCD.

  • + Share This
  • 🔖 Save To Your Account