]> git.saurik.com Git - apple/libdispatch.git/blob - testing/dispatch_timer.c
libdispatch-84.5.3.tar.gz
[apple/libdispatch.git] / testing / dispatch_timer.c
1 #include <stdlib.h>
2 #include <assert.h>
3 #include <stdio.h>
4 #include <string.h>
5
6 #include <dispatch/dispatch.h>
7
8 #include "dispatch_test.h"
9
10 int main(void)
11 {
12 test_start("Dispatch Source Timer");
13
14 dispatch_queue_t main_q = dispatch_get_main_queue();
15 test_ptr("dispatch_get_main_queue", main_q, dispatch_get_current_queue());
16
17 uint64_t j;
18
19 // create several timers and release them.
20 for (j = 1; j <= 5; ++j)
21 {
22 dispatch_source_t s = dispatch_source_timer_create(DISPATCH_TIMER_INTERVAL,
23 (uint64_t)j * (uint64_t)1000000000ull, 0, NULL, dispatch_get_concurrent_queue(0),
24 ^(dispatch_event_t ev) {
25 if (!dispatch_event_get_error(ev, NULL)) {
26 fprintf(stderr, "timer[%lld]\n", j);
27 dispatch_release(dispatch_event_get_source(ev));
28 }
29 });
30 test_ptr_notnull("dispatch_source_timer_create", s);
31 }
32
33 dispatch_source_attr_t attr = dispatch_source_attr_create();
34 dispatch_source_attr_set_finalizer(attr, ^(dispatch_source_t ds) {
35 test_ptr_notnull("finalizer ran", ds);
36 test_stop();
37 });
38
39 __block int i = 0;
40
41 dispatch_source_t s = dispatch_source_timer_create(DISPATCH_TIMER_INTERVAL,
42 1000000000ull,
43 0,
44 attr,
45 main_q,
46 ^(dispatch_event_t ev) {
47 long err;
48 if (dispatch_event_get_error(ev, &err)) {
49 test_errno("dispatch_event_get_error", err, ECANCELED);
50 dispatch_release(dispatch_event_get_source(ev));
51 } else {
52 fprintf(stderr, "%d\n", ++i);
53 if (i >= 3) {
54 dispatch_cancel(dispatch_event_get_source(ev));
55 }
56 }
57 });
58 test_ptr_notnull("dispatch_source_timer_create", s);
59
60 dispatch_release(attr);
61
62 dispatch_main();
63
64 return 0;
65 }