iosmacosgrand-central-dispatchlibdispatch

Grand Central Dispatch without blocks


Is it possible to use GCD without blocks? Is there a way to use GCD using _f variant as mikeash says in his post. I searched around and there is no proof for either sides. is it possible or impossible.

If its doable please give an example.

/Selvin


Solution

  • Of course it is possible! By _f variants Mike just mean set of GCD functions with _f suffix. They are alternatives for usual GCD functions but can accept a user defined function as a parameter instead of blocks. There are plenty of them:

    dispatch_async_f
    dispatch_sync_f
    dispatch_after_f
    dispatch_apply_f
    dispatch_group_async_f
    dispatch_group_notify_f
    dispatch_set_finalizer_f
    dispatch_barrier_async_f
    dispatch_barrier_sync_f
    dispatch_source_set_registration_handler_f
    dispatch_source_set_cancel_handler_f
    dispatch_source_set_event_handler_f
    

    They accept dispatch_function_t parameter (instead of usual dispatch_block_t) which is defined as follows:

    typedef void (*dispatch_function_t)(void*).

    As you see it can accept any user parameter and also a function because of *void pointer. So you can even use dispatch_function_t with function that have no arguments - you can just write a wrapper function like so:

    void func(void) {
      //do any calculations you want here
        }
    void wrapper_function(void*) { func(); }
    dispatch_async_f(queue, 0, &wrapper_function);
    

    Or pass a function pointer as a parameter. Or on the contrary you can use _f variants of GCD functions with user defined functions which can accept any number of arguments via the varargs (variadic functions) - just write a function wrapper for it also as above. As you see _f functions is rather a powerful mechanism and you are not limited only with blocks without parameters for GCD but can use usual functions.