]> git.saurik.com Git - apple/libdispatch.git/blob - testing/dispatch_suspend_timer.c
libdispatch-84.5.3.tar.gz
[apple/libdispatch.git] / testing / dispatch_suspend_timer.c
1 #include <assert.h>
2 #include <stdio.h>
3 #include <string.h>
4
5 #include <dispatch/dispatch.h>
6
7 #include "dispatch_test.h"
8
9 dispatch_source_t tweedledee;
10 dispatch_source_t tweedledum;
11
12 int main(void)
13 {
14 test_start("Dispatch Suspend Timer");
15
16 dispatch_queue_t main_q = dispatch_get_main_queue();
17 test_ptr("dispatch_get_main_queue", main_q, dispatch_get_current_queue());
18
19 __block int i = 0;
20 __block int j = 0;
21
22 dispatch_source_attr_t attr = dispatch_source_attr_create();
23 test_ptr_notnull("dispatch_source_attr_create", attr);
24
25 dispatch_source_attr_set_finalizer(attr, ^(dispatch_source_t ds) {
26 test_ptr_notnull("finalizer ran", ds);
27 if (ds == tweedledum) test_stop();
28 });
29
30 tweedledee = dispatch_source_timer_create(DISPATCH_TIMER_INTERVAL,
31 1000000000ull, 0, attr, main_q, ^(dispatch_event_t ev) {
32 long err;
33 if (dispatch_event_get_error(ev, &err)) {
34 test_errno("dispatch_event_get_error", err, ECANCELED);
35 dispatch_release(dispatch_event_get_source(ev));
36 } else {
37 fprintf(stderr, "%d\n", ++i);
38 if (i == 10) {
39 dispatch_cancel(dispatch_event_get_source(ev));
40 }
41 }
42 });
43 test_ptr_notnull("dispatch_source_timer_create", tweedledee);
44 dispatch_retain(tweedledee);
45
46 tweedledum = dispatch_source_timer_create(DISPATCH_TIMER_INTERVAL,
47 3000000000ull, 0, attr, main_q, ^(dispatch_event_t ev) {
48 long err;
49 if (dispatch_event_get_error(ev, &err)) {
50 test_errno("dispatch_event_get_error", err, ECANCELED);
51 dispatch_release(dispatch_event_get_source(ev));
52 } else {
53 switch(++j) {
54 case 1:
55 fprintf(stderr, "suspending timer for 3 seconds\n");
56 dispatch_suspend(tweedledee);
57 break;
58 case 2:
59 fprintf(stderr, "resuming timer\n");
60 dispatch_resume(tweedledee);
61 dispatch_release(tweedledee);
62 break;
63 default:
64 dispatch_cancel(dispatch_event_get_source(ev));
65 break;
66 }
67 }
68 });
69 test_ptr_notnull("dispatch_source_timer_create", tweedledum);
70
71 dispatch_release(attr);
72
73 dispatch_main();
74
75 return 0;
76 }