Debian Codegraph @

build/future_function_templates/future.c.template

raw
1 #include <stdio.h>
2
3 #include <mongoc/mongoc-array-private.h>
4 #include <mongoc/mongoc-thread-private.h>
5 #include "mock_server/future.h"
6 #include "../test-libmongoc.h"
7
8 {{ header_comment }}
9
10 #define FUTURE_TIMEOUT_ABORT \
11 if (1) { \
12 fflush (stdout); \
13 fprintf (stderr, "%s timed out\n", BSON_FUNC); \
14 fflush (stderr); \
15 abort (); \
16 } else \
17 ((void) 0)
18
19 void
20 future_get_void (future_t *future)
21 {
22 if (future_wait (future)) {
23 return;
24 }
25
26 FUTURE_TIMEOUT_ABORT;
27 }
28
29 {% for T in type_list %}
30 {{ T }}
31 future_get_{{ T }} (future_t *future)
32 {
33 if (future_wait (future)) {
34 return future_value_get_{{ T }} (&future->return_value);
35 }
36
37 FUTURE_TIMEOUT_ABORT;
38 }
39 {% endfor %}
40
41 future_t *
42 future_new (future_value_type_t return_type, int argc)
43 {
44 future_t *future;
45
46 future = (future_t *)bson_malloc0 (sizeof *future);
47 future->return_value.type = return_type;
48 future->argc = argc;
49 future->argv = (future_value_t *)bson_malloc0 ((size_t) argc * sizeof(future_value_t));
50 mongoc_cond_init (&future->cond);
51 bson_mutex_init (&future->mutex);
52
53 return future;
54 }
55
56 future_value_t *
57 future_get_param (future_t *future, int i)
58 {
59 return &future->argv[i];
60 }
61
62 void
63 future_start (future_t *future,
64 BSON_THREAD_FUN_TYPE (start_routine))
65 {
66 int r = mcommon_thread_create (&future->thread,
67 start_routine,
68 (void *) future);
69
70 BSON_ASSERT (!r);
71 }
72
73
74 void
75 future_resolve (future_t *future, future_value_t return_value)
76 {
77 bson_mutex_lock (&future->mutex);
78 BSON_ASSERT (!future->resolved);
79 BSON_ASSERT (future->return_value.type == return_value.type);
80 future->return_value = return_value;
81 future->resolved = true;
82 mongoc_cond_signal (&future->cond);
83 bson_mutex_unlock (&future->mutex);
84 }
85
86
87 bool
88 future_wait_max (future_t *future, int64_t timeout_ms)
89 {
90 int64_t remaining_usec = timeout_ms * 1000;
91 int64_t deadline = bson_get_monotonic_time () + timeout_ms * 1000;
92 bool resolved;
93
94 bson_mutex_lock (&future->mutex);
95 while (!future->resolved && remaining_usec > 0) {
96 mongoc_cond_timedwait (&future->cond, &future->mutex,
97 remaining_usec / 1000);
98 remaining_usec = deadline - bson_get_monotonic_time ();
99 }
100 resolved = future->resolved;
101 bson_mutex_unlock (&future->mutex);
102
103 if (resolved) {
104 future->awaited = true;
105
106 /* free memory */
107 mcommon_thread_join (future->thread);
108 }
109
110 return resolved;
111 }
112
113
114 bool
115 future_wait (future_t *future)
116 {
117 return future_wait_max (future, get_future_timeout_ms ());
118 }
119
120
121 void
122 future_destroy (future_t *future)
123 {
124 BSON_ASSERT (future->awaited);
125 bson_free (future->argv);
126 mongoc_cond_destroy (&future->cond);
127 bson_mutex_destroy (&future->mutex);
128 bson_free (future);
129 }