]> git.saurik.com Git - apple/libdispatch.git/blob - testing/dispatch_group.c
libdispatch-84.5.5.tar.gz
[apple/libdispatch.git] / testing / dispatch_group.c
1 #include <dispatch/dispatch.h>
2 #include <unistd.h>
3 #include <stdarg.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <assert.h>
7 #include <libkern/OSAtomic.h>
8
9 #include "dispatch_test.h"
10
11 #ifndef NSEC_PER_SEC
12 #define NSEC_PER_SEC 1000000000
13 #endif
14
15 dispatch_group_t
16 create_group(size_t count, int delay)
17 {
18 size_t i;
19
20 dispatch_group_t group = dispatch_group_create();
21
22 for (i = 0; i < count; ++i) {
23 dispatch_queue_t queue = dispatch_queue_create(NULL, NULL);
24 assert(queue);
25
26 dispatch_group_async(group, queue, ^{
27 if (delay) {
28 fprintf(stderr, "sleeping...\n");
29 sleep(delay);
30 fprintf(stderr, "done.\n");
31 }
32 });
33
34 dispatch_release(queue);
35 }
36 return group;
37 }
38
39 int
40 main(void)
41 {
42 long res;
43
44 test_start("Dispatch Group");
45
46 dispatch_group_t group;
47
48 group = create_group(100, 0);
49 test_ptr_notnull("dispatch_group_async", group);
50
51 dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
52
53 // should be OK to re-use a group
54 dispatch_group_async(group, dispatch_get_concurrent_queue(0), ^{});
55 dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
56
57 dispatch_release(group);
58 group = NULL;
59
60 group = create_group(3, 7);
61 test_ptr_notnull("dispatch_group_async", group);
62
63 res = dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, 5ull * NSEC_PER_SEC));
64 test_long("dispatch_group_wait", !res, 0);
65
66 // retry after timeout (this time succeed)
67 res = dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, 5ull * NSEC_PER_SEC));
68 test_long("dispatch_group_wait", res, 0);
69
70 dispatch_release(group);
71 group = NULL;
72
73 group = create_group(100, 0);
74 test_ptr_notnull("dispatch_group_async", group);
75
76 dispatch_group_notify(group, dispatch_get_main_queue(), ^{
77 dispatch_queue_t m = dispatch_get_main_queue();
78 dispatch_queue_t c = dispatch_get_current_queue();
79 test_ptr("Notification Received", m, c);
80 test_stop();
81 });
82
83 dispatch_release(group);
84 group = NULL;
85
86 dispatch_main();
87
88 return 0;
89 }