fix
[libex.git] / test / test_task.c
blobc6bbd52e7d3a501704785fcaf9592be1c0eb8e78
1 #include <stdio.h>
2 #include "../include/libex/task.h"
4 int i, t;
5 int timed_wait = 0;
7 static int on_create_slot (pool_slot_t *slot, void *x) {
8 printf("create slot\n");
9 return 0;
12 static void on_destroy_slot (pool_slot_t *x) {
13 printf("destroy slot\n");
16 static int on_msg (void *d, pool_msg_t *msg) {
17 printf("%s\n", (char*)msg->data);
18 free(msg->data);
19 sleep(t);
20 return MSG_DONE;
23 static int on_info (void *d, pool_msg_t *x) {
24 printf("%d: %lu\n", i++, time(0));
25 return MSG_DONE;
28 static void test_1 () {
29 printf(" \n-= test 1 =-\n");
30 pool_t *pool = pool_create();
31 #ifdef __GNUC__
32 pool_setopt(pool, POOL_MAXSLOTS, 8);
33 pool_setopt(pool, POOL_CREATESLOT, on_create_slot);
34 pool_setopt(pool, POOL_DESTROYSLOT, on_destroy_slot);
35 #else
36 pool_setopt_int(pool, POOL_MAXSLOTS, 24);
37 pool_setopt_create(pool, POOL_CREATESLOT, on_create_slot);
38 pool_setopt_destroy(pool, POOL_DESTROYSLOT, on_destroy_slot);
39 #endif
40 pool_start(pool);
41 for (int i = 0; i < 16; ++i) {
42 char *str = malloc(16);
43 usleep(1000);
44 snprintf(str, 16, "i:%d", i);
45 pool_call(pool, on_msg, str, NULL, 0);
47 sleep(2);
48 pool_destroy(pool, timed_wait);
51 static void test_2 () {
52 printf(" \n-= test 2 =-\n");
53 pool_t *pool = pool_create();
54 #ifdef __GNUC__
55 pool_setopt(pool, POOL_MSG, on_info);
56 pool_setopt(pool, POOL_TIMEOUT, 1);
57 pool_setopt(pool, POOL_MAXSLOTS, 1);
58 #else
59 pool_setopt_msg(pool, POOL_MSG, on_info);
60 pool_setopt_int(pool, POOL_TIMEOUT, 1);
61 pool_setopt_int(pool, POOL_MAXSLOTS, 1);
62 #endif
63 i = 0;
64 pool_start(pool);
65 sleep(7);
66 pool_destroy(pool, timed_wait);
69 static int on_msg1 (void *d, pool_msg_t *msg) {
70 int n = (intptr_t)msg->data;
71 printf("%d\n", n);
72 msg->data = (void*)(intptr_t)msg->data - 1;
73 if ((intptr_t)msg->data == 0)
74 return MSG_DONE;
75 return MSG_WAIT;
78 static void test_3 () {
79 printf(" \n-= test 3 =-\n");
80 pool_t *pool = pool_create();
81 #ifdef __GNUC__
82 pool_setopt(pool, POOL_MAXSLOTS, POOL_DEFAULT_SLOTS);
83 #else
84 pool_setopt_int(pool, POOL_MAXSLOTS, POOL_DEFAULT_SLOTS);
85 #endif
86 pool_start(pool);
87 pool_call(pool, on_msg1, (void*)(intptr_t)3, NULL, 0);
88 sleep(2);
89 pool_destroy(pool, timed_wait);
92 int main (int argc, const char *argv[]) {
93 if (argc > 1) {
94 char *tail;
95 timed_wait = strtol(argv[1], &tail, 0);
96 if ('\0' != *tail || ERANGE == errno)
97 timed_wait = 0;
99 test_1();
100 test_2();
101 test_3();
102 return 0;