Threads: handles request with threads
[src/app-framework-binder.git] / src / tests / test-thread.c
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #include <pthread.h>
4 #include <time.h>
5 #include <unistd.h>
6 #include <sys/syscall.h>
7
8 #include <afb/afb-req-itf.h>
9 #include "../afb-thread.h"
10
11 struct foo {
12         int value;
13         int refcount;
14 };
15
16 void addref(void *closure)
17 {
18         struct foo *foo = closure;
19         foo->refcount++;
20 }
21
22 void unref(void *closure)
23 {
24         struct foo *foo = closure;
25         if(!--foo->refcount) {
26                 printf("%06d FREE\n", foo->value);
27                 free(foo);
28         }
29 }
30
31 void fail(void *closure, const char *status, const char *info)
32 {
33         struct foo *foo = closure;
34         printf("%06d ERROR %s\n", foo->value, status);
35 }
36
37 struct afb_req_itf itf = {
38         .json = NULL,
39         .get = NULL,
40
41         .success = NULL,
42         .fail = fail,
43
44         .raw = NULL,
45         .send = NULL,
46
47         .context_get = NULL,
48         .context_set = NULL,
49
50         .addref = addref,
51         .unref = unref,
52
53         .session_close = NULL,
54         .session_set_LOA = NULL,
55
56         .subscribe = NULL,
57         .unsubscribe = NULL,
58
59         .subcall = NULL
60 };
61
62 void process(struct afb_req req)
63 {
64         struct timespec ts;
65         struct foo *foo = req.closure;
66         printf("%06d PROCESS T%d\n", foo->value, (int)syscall(SYS_gettid));
67         ts.tv_sec = 0;
68         ts.tv_nsec = foo->value * 1000;
69 //      nanosleep(&ts, NULL);
70 }
71
72 int main()
73 {
74         int i;
75         struct foo *foo;
76         struct afb_req req;
77         struct timespec ts;
78
79         req.itf = &itf;
80         afb_thread_init(4, 1);
81         for (i = 0 ; i  < 10000 ; i++) {
82                 req.closure = foo = malloc(sizeof *foo);
83                 foo->value = i;
84                 foo->refcount = 1;
85                 afb_thread_call(req, process, 5, (&ts) + (i % 4));
86                 unref(foo);
87                 ts.tv_sec = 0;
88                 ts.tv_nsec = 1000000;
89 //              nanosleep(&ts, NULL);
90         }
91         ts.tv_sec = 1;
92         ts.tv_nsec = 0;
93         nanosleep(&ts, NULL);
94         afb_thread_terminate();
95 }
96
97
98
99