Grand Central Dispatch without blocks

做~自己de王妃 提交于 2019-12-04 21:53:55

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.

Rui Peres

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!