dispatch_pingpong.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2008-2011 Apple Inc. All rights reserved.
  3. *
  4. * @APPLE_APACHE_LICENSE_HEADER_START@
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * @APPLE_APACHE_LICENSE_HEADER_END@
  19. */
  20. #include <dispatch/dispatch.h>
  21. #include <stdio.h>
  22. #include <bsdtests.h>
  23. #include "dispatch_test.h"
  24. uint32_t count = 0;
  25. const uint32_t final = 1000000; // 10M
  26. static void
  27. pingpongloop(dispatch_group_t group, dispatch_queue_t ping, dispatch_queue_t pong, size_t counter)
  28. {
  29. //printf("[%p] %s: %lu\n", (void*)(uintptr_t)pthread_self(), dispatch_queue_get_label(dispatch_get_current_queue()), counter);
  30. if (counter < final) {
  31. dispatch_group_async(group, pong, ^{ pingpongloop(group, pong, ping, counter+1); });
  32. } else {
  33. count = (uint32_t)counter;
  34. }
  35. }
  36. int
  37. main(void)
  38. {
  39. dispatch_test_start("Dispatch Ping Pong");
  40. dispatch_queue_t ping = dispatch_queue_create("ping", NULL);
  41. test_ptr_notnull("dispatch_queue_create(ping)", ping);
  42. dispatch_queue_t pong = dispatch_queue_create("pong", NULL);
  43. test_ptr_notnull("dispatch_queue_create(pong)", pong);
  44. dispatch_group_t group = dispatch_group_create();
  45. test_ptr_notnull("dispatch_group_create", group);
  46. pingpongloop(group, ping, pong, 0);
  47. dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
  48. test_long("count", count, final);
  49. dispatch_release(ping);
  50. dispatch_release(pong);
  51. dispatch_release(group);
  52. test_stop();
  53. return 0;
  54. }