GLib的Timeout Source只能指定固定的时间间隔,因此,不适合做为精确计时使用(精度接近播放器的播放时间)。从2.36开始,GLib提供了一种方法,可以在不使用Timeout Source的情况下,使一个Source的Dispatch函数在指定的时间点被触发,从而提高计时精度。用法如下:
1. 创建一个通用Source和Mainloop
static GSourceFuncs ptimeFuncs =
{
.dispatch = ptimeDispatch //prepare&check回调均为NULL
};
GSource * _src = g_source_new( &ptimeFuncs, sizeof( GSource ));
GMainLoop * _mainloop = g_main_loop_new( NULL, FALSE );
2. 将Source关联到Default Context上,并使其立刻执行
g_source_attach( _src, NULL );
g_source_set_ready_time( _src, 0 ); //设置为0表示立即执行
g_main_loop_run( _mainloop );
3. Dispatch回调函数
static gboolean ptimeDispatch( GSource * source, GSourceFunc callback, gpointer user_data )
{
static int _int = 100000;
g_message( "%s is fired", __func__ );
g_source_set_ready_time( source, g_source_get_time( source ) + _int ); //设置Source下次被触发的时间,该时间要通过计算得到,非相对时间。
_int += 100000;
return G_SOURCE_CONTINUE;
} /* ----- end of static function ptimeDispatch ----- */