Storing Custom Context Information with a Queue
All dispatch objects (including dispatch queues) allow you to associate custom context data with the object.To set and get this data on a given object, you use the dispatch_set_context and dispatch_get_context functions. The system does not use your custom data in any way, and it is up to you to both allocate anddeallocate the data at the appropriate times.
<div class="page" title="Page 46"><div class="layoutArea"><div class="column"><p><span style="font-size: 10pt; font-family: MyriadSet;">// Installing a queue clean up function </span></p></div></div></div>
void myFinalizerFunction(void *context)
{
MyDataContext* theData = (MyDataContext*)context;
// Clean up the contents of the structure
myCleanUpDataContextFunction(theData);
// Now release the structure itself.
free(theData);
}
dispatch_queue_t createMyQueue()
{
MyDataContext* data = (MyDataContext*) malloc(sizeof(MyDataContext));
myInitializeDataContextFunction(data);
// Create the queue and set the context data.
dispatch_queue_t serialQueue =
dispatch_queue_create("com.example.CriticalTaskQueue", NULL);
if (serialQueue)
{
dispatch_set_context(serialQueue, data);
dispatch_set_finalizer_f(serialQueue, &myFinalizerFunction);
}
return serialQueue;
}