dispatch_sync_on_main.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (c) 2009-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 <dispatch/private.h>
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  25. #include <unistd.h>
  26. #endif
  27. #include <CoreFoundation/CoreFoundation.h>
  28. #include <bsdtests.h>
  29. #include "dispatch_test.h"
  30. const int32_t final = 10;
  31. int global_count = 0;
  32. static void
  33. work(void* ctxt __attribute__((unused)))
  34. {
  35. if (global_count == INT_MAX) {
  36. test_stop();
  37. }
  38. printf("Firing timer on main %d\n", ++global_count);
  39. dispatch_after_f(dispatch_time(0, 100000*NSEC_PER_USEC),
  40. dispatch_get_main_queue(), NULL, work);
  41. }
  42. int
  43. main(void)
  44. {
  45. dispatch_test_start("Dispatch Sync on main"); // <rdar://problem/7181849>
  46. dispatch_queue_t dq = dispatch_queue_create("foo.bar", NULL);
  47. dispatch_async(dq, ^{
  48. dispatch_async_f(dispatch_get_main_queue(), NULL, work);
  49. int i;
  50. for (i=0; i<final; ++i) {
  51. dispatch_sync(dispatch_get_main_queue(), ^{
  52. printf("Calling sync %d\n", i);
  53. test_long("sync on main", pthread_main_np(), 1);
  54. if (i == final-1) {
  55. global_count = INT_MAX;
  56. }
  57. });
  58. const struct timespec t = {.tv_nsec = 50000*NSEC_PER_USEC};
  59. nanosleep(&t, NULL);
  60. }
  61. });
  62. dispatch_release(dq);
  63. CFRunLoopRun();
  64. return 0;
  65. }