Fix bug in recycling jobs
[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 #include "../jobs.h"
11
12 struct foo {
13         int value;
14         int refcount;
15 };
16
17 void addref(void *closure)
18 {
19         struct foo *foo = closure;
20         foo->refcount++;
21 }
22
23 void unref(void *closure)
24 {
25         struct foo *foo = closure;
26         if(!--foo->refcount) {
27                 printf("%06d FREE\n", foo->value);
28                 free(foo);
29         }
30 }
31
32 void fail(void *closure, const char *status, const char *info)
33 {
34         struct foo *foo = closure;
35         printf("%06d ERROR %s\n", foo->value, status);
36 }
37
38 struct afb_req_itf itf = {
39         .json = NULL,
40         .get = NULL,
41
42         .success = NULL,
43         .fail = fail,
44
45         .raw = NULL,
46         .send = NULL,
47
48         .context_get = NULL,
49         .context_set = NULL,
50
51         .addref = addref,
52         .unref = unref,
53
54         .session_close = NULL,
55         .session_set_LOA = NULL,
56
57         .subscribe = NULL,
58         .unsubscribe = NULL,
59
60         .subcall = NULL
61 };
62
63 void process(struct afb_req req)
64 {
65         struct timespec ts;
66         struct foo *foo = req.closure;
67         printf("%06d PROCESS T%d\n", foo->value, (int)syscall(SYS_gettid));
68         ts.tv_sec = 0;
69         ts.tv_nsec = foo->value * 1000;
70 //      nanosleep(&ts, NULL);
71 }
72
73 int main()
74 {
75         int i;
76         struct foo *foo;
77         struct afb_req req;
78         struct timespec ts;
79
80         req.itf = &itf;
81         jobs_init(4, 0, 20000);
82         for (i = 0 ; i  < 10000 ; i++) {
83                 req.closure = foo = malloc(sizeof *foo);
84                 foo->value = i;
85                 foo->refcount = 1;
86                 afb_thread_req_call(req, process, 5, (&ts) + (i % 7));
87                 unref(foo);
88                 ts.tv_sec = 0;
89                 ts.tv_nsec = 1000000;
90 //              nanosleep(&ts, NULL);
91         }
92         ts.tv_sec = 1;
93         ts.tv_nsec = 0;
94         nanosleep(&ts, NULL);
95         jobs_terminate();
96 }
97
98
99
100