dispatch_api.3 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. .\" Copyright (c) 2008-2009 Apple Inc. All rights reserved.
  2. .Dd May 1, 2009
  3. .Dt dispatch_api 3
  4. .Os Darwin
  5. .Sh NAME
  6. .Nm dispatch_api
  7. .Nd Designing API using dispatch
  8. .Sh DESCRIPTION
  9. The following is a brief summary of some of the common design patterns to
  10. consider when designing and implementing API in terms of dispatch queues
  11. and blocks.
  12. .Pp
  13. A general recommendation is to allow both a callback block and target dispatch
  14. queue to be specified. This gives the application the greatest flexibility in
  15. handling asynchronous events.
  16. .Pp
  17. It's also recommended that interfaces take only a single block as the last
  18. parameter. This is both for consistency across projects, as well as the visual
  19. aesthetics of multiline blocks that are declared inline. The dispatch queue to
  20. which the block will be submitted should immediately precede the block argument
  21. (second-to-last argument). For example:
  22. .Pp
  23. .Bd -literal -offset indent
  24. read_async(file, callback_queue, ^{
  25. printf("received callback.\\n");
  26. });
  27. .Ed
  28. .Pp
  29. When function pointer alternatives to interfaces that take blocks are provided,
  30. the argument order of the function signature should be identical to the block
  31. variant; with the exception that the block argument is replaced with a context
  32. pointer, and a new last parameter is added, which is the function to call.
  33. .Pp
  34. The function based callback should pass the context pointer as the first
  35. argument, and the subsequent arguments should be identical to the block based
  36. variant (albeit offset by one in order).
  37. .Pp
  38. It is also important to use consistent naming. The dispatch API, for example,
  39. uses the suffix "_f" for function based variants.
  40. .Pp
  41. .Sh SEE ALSO
  42. .Xr dispatch 3 ,
  43. .Xr dispatch_async 3 ,
  44. .Xr dispatch_queue_create 3