dispatch_timer_timeout.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (c) 2010-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 <assert.h>
  21. #include <stdio.h>
  22. #include <string.h>
  23. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  24. #include <sys/time.h>
  25. #endif
  26. #include <dispatch/dispatch.h>
  27. #include <bsdtests.h>
  28. #include "dispatch_test.h"
  29. int
  30. main(void)
  31. {
  32. dispatch_test_start("Dispatch Source Timeout"); // <rdar://problem/8015967>
  33. uint64_t mini_interval = 100ull; // 100 ns
  34. uint64_t long_interval = 2000000000ull; // 2 secs
  35. dispatch_queue_t timer_queue = dispatch_queue_create("timer_queue", NULL);
  36. __block int value_to_be_changed = 5;
  37. __block int fired = 0;
  38. dispatch_source_t mini_timer, long_timer;
  39. mini_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timer_queue);
  40. dispatch_source_set_event_handler(mini_timer, ^{
  41. printf("Firing mini-timer %d\n", ++fired);
  42. printf("Suspending mini-timer queue\n");
  43. dispatch_suspend(timer_queue);
  44. });
  45. dispatch_source_set_timer(mini_timer, DISPATCH_TIME_NOW, mini_interval, 0);
  46. long_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
  47. dispatch_source_set_event_handler(long_timer, ^{
  48. printf("Firing long timer\n");
  49. value_to_be_changed = 10;
  50. dispatch_source_cancel(long_timer);
  51. });
  52. dispatch_source_set_timer(long_timer,
  53. dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC) ,
  54. long_interval, 0);
  55. dispatch_resume(mini_timer);
  56. dispatch_resume(long_timer);
  57. sleep(6);
  58. test_long("Checking final value", value_to_be_changed, 10);
  59. test_long("Mini-timer fired", fired, 1);
  60. dispatch_source_cancel(mini_timer);
  61. dispatch_release(mini_timer);
  62. dispatch_resume(timer_queue);
  63. dispatch_release(timer_queue);
  64. dispatch_release(long_timer);
  65. test_stop();
  66. return 0;
  67. }