various GLib tests: plug memory leaks
[platform/upstream/glib.git] / glib / tests / timeout.c
1 #include <glib.h>
2 #include <unistd.h>
3
4 static GMainLoop *loop;
5
6 static gboolean
7 stop_waiting (gpointer data)
8 {
9   g_main_loop_quit (loop);
10
11   return FALSE;
12 }
13
14 static gboolean
15 function (gpointer data)
16 {
17   g_assert_not_reached ();
18 }
19
20 static void
21 test_seconds (void)
22 {
23   /* Bug 642052 mentions that g_timeout_add_seconds(21475) schedules a
24    * job that runs once per second.
25    *
26    * Test that that isn't true anymore by scheduling two jobs:
27    *   - one, as above
28    *   - another that runs in 2100ms
29    *
30    * If everything is working properly, the 2100ms one should run first
31    * (and exit the mainloop).  If we ever see the 21475 second job run
32    * then we have trouble (since it ran in less than 2 seconds).
33    *
34    * We need a timeout of at least 2 seconds because
35    * g_timeout_add_second can add as much as an additional second of
36    * latency.
37    */
38   loop = g_main_loop_new (NULL, FALSE);
39
40   g_timeout_add (2100, stop_waiting, NULL);
41   g_timeout_add_seconds (21475, function, NULL);
42
43   g_main_loop_run (loop);
44   g_main_loop_unref (loop);
45 }
46
47 static gint64 last_time;
48 static gint count;
49
50 static gboolean
51 test_func (gpointer data)
52 {
53   gint64 current_time;
54
55   current_time = g_get_monotonic_time ();
56
57   /* We accept 2 on the first iteration because _add_seconds() can
58    * have an initial latency of 1 second, see its documentation.
59    */
60   if (count == 0)
61     g_assert (current_time / 1000000 - last_time / 1000000 <= 2);
62   else
63     g_assert (current_time / 1000000 - last_time / 1000000 == 1);
64
65   last_time = current_time;
66   count++;
67
68   /* Make the timeout take up to 0.1 seconds.
69    * We should still get scheduled for the next second.
70    */
71   g_usleep (count * 10000);
72
73   if (count < 10)
74     return TRUE;
75
76   g_main_loop_quit (loop);
77
78   return FALSE;
79 }
80
81 static void
82 test_rounding (void)
83 {
84   loop = g_main_loop_new (NULL, FALSE);
85
86   last_time = g_get_monotonic_time ();
87   g_timeout_add_seconds (1, test_func, NULL);
88
89   g_main_loop_run (loop);
90   g_main_loop_unref (loop);
91 }
92
93 int
94 main (int argc, char *argv[])
95 {
96   g_test_init (&argc, &argv, NULL);
97
98   g_test_add_func ("/timeout/seconds", test_seconds);
99   g_test_add_func ("/timeout/rounding", test_rounding);
100
101   return g_test_run ();
102 }