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
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.
Yes you can, as stated on the article:
You can use GCD without blocks, via the _f variants provided for every GCD function that takes a block
If you look at the GCD documentation you can check the variants. If you need a quick example there are many on SO:
来源:https://stackoverflow.com/questions/17811414/grand-central-dispatch-without-blocks