当前位置: 代码迷 >> 综合 >> glib库简单计时器的实现
  详细解决方案

glib库简单计时器的实现

热度:3   发布时间:2024-01-21 01:02:50.0
#include <stdio.h>
#include <glib.h>

#define INTERVALS    10    //间隔10ms
#define COUNTER        1000    //计时间隔数

GMainLoop *loop;
gint count = COUNTER;

gboolean callback(gpointer arg)
{
    count--;

    if( 0 == count%100 )
    {
        printf("%d \n", count/100);
    }
    if ( 0 == count )
    {
        g_main_loop_quit(loop);
        return FALSE;
    }    
    return TRUE;
}

int main()
{
    if( 0 == g_thread_supported() )
    {
        g_thread_init(NULL);
    }
    
    loop = g_main_loop_new(NULL, FALSE);
    
    g_timeout_add(INTERVALS, callback, NULL);  /*每隔INTERVALS秒钟调用一次回调函数,当调用COUNTER次后,执行g_main_loop_quit(loop),退出事件循环*/
    g_main_loop_run(loop);
    
    g_main_loop_unref(loop);
}