Merge branch 'g-clear-pointer-no-side-effects' into 'master'
[glib.git] / glib / tests / timeout.c
blobce7dd096551d04a5bdb59cfc2b8e83d403d1f8a1
1 #include <glib.h>
2 #ifdef G_OS_UNIX
3 #include <unistd.h>
4 #endif
6 static GMainLoop *loop;
8 static gboolean
9 stop_waiting (gpointer data)
11 g_main_loop_quit (loop);
13 return G_SOURCE_REMOVE;
16 static gboolean
17 function (gpointer data)
19 g_assert_not_reached ();
21 return G_SOURCE_REMOVE;
24 static void
25 test_seconds (void)
27 guint id;
29 /* Bug 642052 mentions that g_timeout_add_seconds(21475) schedules a
30 * job that runs once per second.
32 * Test that that isn't true anymore by scheduling two jobs:
33 * - one, as above
34 * - another that runs in 2100ms
36 * If everything is working properly, the 2100ms one should run first
37 * (and exit the mainloop). If we ever see the 21475 second job run
38 * then we have trouble (since it ran in less than 2 seconds).
40 * We need a timeout of at least 2 seconds because
41 * g_timeout_add_second can add as much as an additional second of
42 * latency.
44 loop = g_main_loop_new (NULL, FALSE);
46 g_timeout_add (2100, stop_waiting, NULL);
47 id = g_timeout_add_seconds (21475, function, NULL);
49 g_main_loop_run (loop);
50 g_main_loop_unref (loop);
52 g_source_remove (id);
55 static gint64 last_time;
56 static gint count;
58 static gboolean
59 test_func (gpointer data)
61 gint64 current_time;
63 current_time = g_get_monotonic_time ();
65 /* We accept 2 on the first iteration because _add_seconds() can
66 * have an initial latency of 1 second, see its documentation.
68 if (count == 0)
69 g_assert (current_time / 1000000 - last_time / 1000000 <= 2);
70 else
71 g_assert (current_time / 1000000 - last_time / 1000000 == 1);
73 last_time = current_time;
74 count++;
76 /* Make the timeout take up to 0.1 seconds.
77 * We should still get scheduled for the next second.
79 g_usleep (count * 10000);
81 if (count < 10)
82 return TRUE;
84 g_main_loop_quit (loop);
86 return FALSE;
89 static void
90 test_rounding (void)
92 loop = g_main_loop_new (NULL, FALSE);
94 last_time = g_get_monotonic_time ();
95 g_timeout_add_seconds (1, test_func, NULL);
97 g_main_loop_run (loop);
98 g_main_loop_unref (loop);
102 main (int argc, char *argv[])
104 g_test_init (&argc, &argv, NULL);
106 g_test_add_func ("/timeout/seconds", test_seconds);
107 g_test_add_func ("/timeout/rounding", test_rounding);
109 return g_test_run ();