6.4. Dispatching Tasks to Grand Central Dispatch
Problem
You want to learn how to create a block of code that can be executed by GCD.
Solution
There are two ways to submit tasks to dispatch queues:
Block Objects (see Recipe 6.1)
C functions
Discussion
Block objects are the best way of utilizing GCD and its enormous power. Some GCD functions have been extended to allow programmers to use C functions instead of block objects. However, the truth is that only a limited set of GCD functions allow programmers to use C functions, so please do read the recipe about block objects (Recipe 6.1) before proceeding any further.
C functions that have to be supplied to various GCD functions
should be of type dispatch_function_t, which is defined as
follows in the Apple libraries:
typedefvoid(*dispatch_function_t)(void*);
So if we want to create a function named, for instance, myGCDFunction, we would have to implement it
in this way:
voidmyGCDFunction(void*paraContext){/* Do the work here */}
Note
The paraContext
parameter refers to the context that GCD allows programmers to
pass to their C functions when they dispatch tasks to them. We will
learn about this shortly.
Block objects that get passed to GCD functions don’t always follow the same structure. Some must accept parameters and some shouldn’t, but none of the block objects submitted to GCD return a value.
In the next three sections, you will learn how to submit tasks to GCD for execution whether they are in the form of block objects or C functions. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access