e075c5722d0ba1c0c3944d9b64b19b7a29892a14
[platform/upstream/glib.git] / gobject / tests / threadtests.c
1 /* GLib testing framework examples and tests
2  * Copyright (C) 2008 Imendio AB
3  * Authors: Tim Janik
4  *
5  * This work is provided "as is"; redistribution and modification
6  * in whole or in part, in any medium, physical or electronic is
7  * permitted without restriction.
8  *
9  * This work is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12  *
13  * In no event shall the authors or contributors be liable for any
14  * direct, indirect, incidental, special, exemplary, or consequential
15  * damages (including, but not limited to, procurement of substitute
16  * goods or services; loss of use, data, or profits; or business
17  * interruption) however caused and on any theory of liability, whether
18  * in contract, strict liability, or tort (including negligence or
19  * otherwise) arising in any way out of the use of this software, even
20  * if advised of the possibility of such damage.
21  */
22 #define GLIB_DISABLE_DEPRECATION_WARNINGS
23 #include <glib.h>
24 #include <glib-object.h>
25
26 static volatile int mtsafe_call_counter = 0; /* multi thread safe call counter */
27 static int          unsafe_call_counter = 0; /* single-threaded call counter */
28 static GCond sync_cond;
29 static GMutex sync_mutex;
30
31 #define NUM_COUNTER_INCREMENTS 100000
32
33 static void
34 call_counter_init (gpointer tclass)
35 {
36   int i;
37   for (i = 0; i < NUM_COUNTER_INCREMENTS; i++)
38     {
39       int saved_unsafe_call_counter = unsafe_call_counter;
40       g_atomic_int_add (&mtsafe_call_counter, 1); /* real call count update */
41       g_thread_yield(); /* let concurrent threads corrupt the unsafe_call_counter state */
42       unsafe_call_counter = 1 + saved_unsafe_call_counter; /* non-atomic counter update */
43     }
44 }
45
46 static void interface_per_class_init (void) { call_counter_init (NULL); }
47
48 /* define 3 test interfaces */
49 typedef GTypeInterface MyFace0Interface;
50 static GType my_face0_get_type (void);
51 G_DEFINE_INTERFACE (MyFace0, my_face0, G_TYPE_OBJECT);
52 static void my_face0_default_init (MyFace0Interface *iface) { call_counter_init (iface); }
53 typedef GTypeInterface MyFace1Interface;
54 static GType my_face1_get_type (void);
55 G_DEFINE_INTERFACE (MyFace1, my_face1, G_TYPE_OBJECT);
56 static void my_face1_default_init (MyFace1Interface *iface) { call_counter_init (iface); }
57
58 /* define 3 test objects, adding interfaces 0 & 1, and adding interface 2 after class initialization */
59 typedef GObject         MyTester0;
60 typedef GObjectClass    MyTester0Class;
61 static GType my_tester0_get_type (void);
62 G_DEFINE_TYPE_WITH_CODE (MyTester0, my_tester0, G_TYPE_OBJECT,
63                          G_IMPLEMENT_INTERFACE (my_face0_get_type(), interface_per_class_init);
64                          G_IMPLEMENT_INTERFACE (my_face1_get_type(), interface_per_class_init);
65                          );
66 static void my_tester0_init (MyTester0*t) {}
67 static void my_tester0_class_init (MyTester0Class*c) { call_counter_init (c); }
68 typedef GObject         MyTester1;
69 typedef GObjectClass    MyTester1Class;
70
71 /* Disabled for now (see https://bugzilla.gnome.org/show_bug.cgi?id=687659) */
72 #if 0
73 typedef GTypeInterface MyFace2Interface;
74 static GType my_face2_get_type (void);
75 G_DEFINE_INTERFACE (MyFace2, my_face2, G_TYPE_OBJECT);
76 static void my_face2_default_init (MyFace2Interface *iface) { call_counter_init (iface); }
77
78 static GType my_tester1_get_type (void);
79 G_DEFINE_TYPE_WITH_CODE (MyTester1, my_tester1, G_TYPE_OBJECT,
80                          G_IMPLEMENT_INTERFACE (my_face0_get_type(), interface_per_class_init);
81                          G_IMPLEMENT_INTERFACE (my_face1_get_type(), interface_per_class_init);
82                          );
83 static void my_tester1_init (MyTester1*t) {}
84 static void my_tester1_class_init (MyTester1Class*c) { call_counter_init (c); }
85 typedef GObject         MyTester2;
86 typedef GObjectClass    MyTester2Class;
87 static GType my_tester2_get_type (void);
88 G_DEFINE_TYPE_WITH_CODE (MyTester2, my_tester2, G_TYPE_OBJECT,
89                          G_IMPLEMENT_INTERFACE (my_face0_get_type(), interface_per_class_init);
90                          G_IMPLEMENT_INTERFACE (my_face1_get_type(), interface_per_class_init);
91                          );
92 static void my_tester2_init (MyTester2*t) {}
93 static void my_tester2_class_init (MyTester2Class*c) { call_counter_init (c); }
94
95 static gpointer
96 tester_init_thread (gpointer data)
97 {
98   const GInterfaceInfo face2_interface_info = { (GInterfaceInitFunc) interface_per_class_init, NULL, NULL };
99   gpointer klass;
100   /* first, syncronize with other threads,
101    * then run interface and class initializers,
102    * using unsafe_call_counter concurrently
103    */
104   g_mutex_lock (&sync_mutex);
105   g_mutex_unlock (&sync_mutex);
106   /* test default interface initialization for face0 */
107   g_type_default_interface_unref (g_type_default_interface_ref (my_face0_get_type()));
108   /* test class initialization, face0 per-class initializer, face1 default and per-class initializer */
109   klass = g_type_class_ref ((GType) data);
110   /* test face2 default and per-class initializer, after class_init */
111   g_type_add_interface_static (G_TYPE_FROM_CLASS (klass), my_face2_get_type(), &face2_interface_info);
112   /* cleanups */
113   g_type_class_unref (klass);
114   return NULL;
115 }
116
117 static void
118 test_threaded_class_init (void)
119 {
120   GThread *t1, *t2, *t3;
121
122   /* pause newly created threads */
123   g_mutex_lock (&sync_mutex);
124
125   /* create threads */
126   t1 = g_thread_create (tester_init_thread, (gpointer) my_tester0_get_type(), TRUE, NULL);
127   t2 = g_thread_create (tester_init_thread, (gpointer) my_tester1_get_type(), TRUE, NULL);
128   t3 = g_thread_create (tester_init_thread, (gpointer) my_tester2_get_type(), TRUE, NULL);
129
130   /* execute threads */
131   g_mutex_unlock (&sync_mutex);
132   while (g_atomic_int_get (&mtsafe_call_counter) < (3 + 3 + 3 * 3) * NUM_COUNTER_INCREMENTS)
133     {
134       if (g_test_verbose())
135         g_print ("Initializers counted: %u\n", g_atomic_int_get (&mtsafe_call_counter));
136       g_usleep (50 * 1000); /* wait for threads to complete */
137     }
138   if (g_test_verbose())
139     g_print ("Total initializers: %u\n", g_atomic_int_get (&mtsafe_call_counter));
140   /* ensure non-corrupted counter updates */
141   g_assert_cmpint (g_atomic_int_get (&mtsafe_call_counter), ==, unsafe_call_counter);
142
143   g_thread_join (t1);
144   g_thread_join (t2);
145   g_thread_join (t3);
146 }
147 #endif
148
149 typedef struct {
150   GObject parent;
151   char   *name;
152 } PropTester;
153 typedef GObjectClass    PropTesterClass;
154 static GType prop_tester_get_type (void);
155 G_DEFINE_TYPE (PropTester, prop_tester, G_TYPE_OBJECT);
156 #define PROP_NAME 1
157 static void
158 prop_tester_init (PropTester* t)
159 {
160   if (t->name == NULL)
161     ; /* neds unit test framework initialization: g_test_bug ("race initializing properties"); */
162 }
163 static void
164 prop_tester_set_property (GObject        *object,
165                           guint           property_id,
166                           const GValue   *value,
167                           GParamSpec     *pspec)
168 {}
169 static void
170 prop_tester_class_init (PropTesterClass *c)
171 {
172   int i;
173   GParamSpec *param;
174   GObjectClass *gobject_class = G_OBJECT_CLASS (c);
175
176   gobject_class->set_property = prop_tester_set_property; /* silence GObject checks */
177
178   g_mutex_lock (&sync_mutex);
179   g_cond_signal (&sync_cond);
180   g_mutex_unlock (&sync_mutex);
181
182   for (i = 0; i < 100; i++) /* wait a bit. */
183     g_thread_yield();
184
185   call_counter_init (c);
186   param = g_param_spec_string ("name", "name_i18n",
187                                "yet-more-wasteful-i18n",
188                                NULL,
189                                G_PARAM_CONSTRUCT_ONLY | G_PARAM_WRITABLE |
190                                G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB |
191                                G_PARAM_STATIC_NICK);
192   g_object_class_install_property (gobject_class, PROP_NAME, param);
193 }
194
195 static gpointer
196 object_create (gpointer data)
197 {
198   GObject *obj = g_object_new (prop_tester_get_type(), "name", "fish", NULL);
199   g_object_unref (obj);
200   return NULL;
201 }
202
203 static void
204 test_threaded_object_init (void)
205 {
206   GThread *creator;
207   g_mutex_lock (&sync_mutex);
208
209   creator = g_thread_create (object_create, NULL, TRUE, NULL);
210   /* really provoke the race */
211   g_cond_wait (&sync_cond, &sync_mutex);
212
213   object_create (NULL);
214   g_mutex_unlock (&sync_mutex);
215
216   g_thread_join (creator);
217 }
218
219 typedef struct {
220     MyTester0 *strong;
221     guint unref_delay;
222 } UnrefInThreadData;
223
224 static gpointer
225 unref_in_thread (gpointer p)
226 {
227   UnrefInThreadData *data = p;
228
229   g_usleep (data->unref_delay);
230   g_object_unref (data->strong);
231
232   return NULL;
233 }
234
235 /* undefine to see this test fail without GWeakRef */
236 #define HAVE_G_WEAK_REF
237
238 #define SLEEP_MIN_USEC 1
239 #define SLEEP_MAX_USEC 10
240
241 static void
242 test_threaded_weak_ref (void)
243 {
244   guint i;
245   guint get_wins = 0, unref_wins = 0;
246   guint n;
247
248   if (g_test_thorough ())
249     n = NUM_COUNTER_INCREMENTS;
250   else
251     n = NUM_COUNTER_INCREMENTS / 20;
252
253   for (i = 0; i < n; i++)
254     {
255       UnrefInThreadData data;
256 #ifdef HAVE_G_WEAK_REF
257       /* GWeakRef<MyTester0> in C++ terms */
258       GWeakRef weak;
259 #else
260       gpointer weak;
261 #endif
262       MyTester0 *strengthened;
263       guint get_delay;
264       GThread *thread;
265       GError *error = NULL;
266
267       if (g_test_verbose () && (i % (n/20)) == 0)
268         g_print ("%u%%\n", ((i * 100) / n));
269
270       /* Have an object and a weak ref to it */
271       data.strong = g_object_new (my_tester0_get_type (), NULL);
272
273 #ifdef HAVE_G_WEAK_REF
274       g_weak_ref_init (&weak, data.strong);
275 #else
276       weak = data.strong;
277       g_object_add_weak_pointer ((GObject *) weak, &weak);
278 #endif
279
280       /* Delay for a random time on each side of the race, to perturb the
281        * timing. Ideally, we want each side to win half the races; on
282        * smcv's laptop, these timings are about right.
283        */
284       data.unref_delay = g_random_int_range (SLEEP_MIN_USEC / 2, SLEEP_MAX_USEC / 2);
285       get_delay = g_random_int_range (SLEEP_MIN_USEC, SLEEP_MAX_USEC);
286
287       /* One half of the race is to unref the shared object */
288       thread = g_thread_create (unref_in_thread, &data, TRUE, &error);
289       g_assert_no_error (error);
290
291       /* The other half of the race is to get the object from the "global
292        * singleton"
293        */
294       g_usleep (get_delay);
295
296 #ifdef HAVE_G_WEAK_REF
297       strengthened = g_weak_ref_get (&weak);
298 #else
299       /* Spot the unsafe pointer access! In GDBusConnection this is rather
300        * better-hidden, but ends up with essentially the same thing, albeit
301        * cleared in dispose() rather than by a traditional weak pointer
302        */
303       strengthened = weak;
304
305       if (strengthened != NULL)
306         g_object_ref (strengthened);
307 #endif
308
309       if (strengthened != NULL)
310         g_assert (G_IS_OBJECT (strengthened));
311
312       /* Wait for the thread to run */
313       g_thread_join (thread);
314
315       if (strengthened != NULL)
316         {
317           get_wins++;
318           g_assert (G_IS_OBJECT (strengthened));
319           g_object_unref (strengthened);
320         }
321       else
322         {
323           unref_wins++;
324         }
325
326 #ifdef HAVE_G_WEAK_REF
327       g_weak_ref_clear (&weak);
328 #else
329       if (weak != NULL)
330         g_object_remove_weak_pointer (weak, &weak);
331 #endif
332     }
333
334   if (g_test_verbose ())
335     g_print ("Race won by get %u times, unref %u times\n",
336              get_wins, unref_wins);
337 }
338
339 int
340 main (int   argc,
341       char *argv[])
342 {
343   g_test_init (&argc, &argv, NULL);
344
345   /* g_test_add_func ("/GObject/threaded-class-init", test_threaded_class_init); */
346   g_test_add_func ("/GObject/threaded-object-init", test_threaded_object_init);
347   g_test_add_func ("/GObject/threaded-weak-ref", test_threaded_weak_ref);
348
349   return g_test_run();
350 }