Tizen 2.1 base
[platform/upstream/gcd.git] / kqueue-1.0.4 / test / libdispatch / main.c
1 /*
2  * Copyright (c) 2009 Mark Heily <mark@heily.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20
21 #include <pthread.h> 
22 #include <sys/event.h> 
23 #include <dispatch/dispatch.h> 
24
25 pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
26 int testnum;
27
28 void test_countdown(void);
29
30 void
31 say_hello(void *arg)
32 {
33         puts("hello");
34         test_countdown();
35 }
36
37 void
38 final_countdown(void *arg, size_t count)
39 {
40         static int europe = 10;
41
42         if (europe == 0) {
43                 printf("It's the final countdown..\n");
44                 exit(0);
45         } else {
46                 printf("%d.. ", europe);
47                 fflush(stdout);
48         }
49
50         pthread_mutex_lock(&mtx);
51         europe--;
52         pthread_mutex_unlock(&mtx);
53 }
54
55 /* Adapted from:
56      http://developer.apple.com/mac/articles/cocoa/introblocksgcd.html
57 */
58 void
59 test_timer()
60 {
61         dispatch_source_t timer;
62         dispatch_time_t now;
63
64     timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, 
65                         dispatch_get_current_queue()); //NOTE: q_default doesn't work
66         now = dispatch_walltime(DISPATCH_TIME_NOW, 0);
67         dispatch_source_set_timer(timer, now, 1, 1);
68         dispatch_source_set_event_handler_f(timer, say_hello);
69         puts("starting timer\n");
70 }
71
72 void
73 test_countdown(void)
74 {
75         dispatch_apply_f(15,
76                         dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),
77                         NULL, final_countdown);
78 }
79
80
81 int 
82 main(int argc, char **argv)
83 {
84     while (argc) {
85 #if TODO
86         if (strcmp(argv[0], "--no-proc") == 0)
87             test_proc = 0;
88 #endif
89         argv++;
90         argc--;
91     }
92
93         test_timer();
94
95         dispatch_main();
96     printf("\n---\n"
97             "+OK All %d tests completed.\n", testnum - 1);
98     return (0);
99 }