glib学习-- timer使用

时间:2020-12-15 23:54:49

如果之让定时器执行一次,回调函数返回false,如果返回true,会定时执行。

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <glib.h>

#define true 1
#define false 0

int id = 0;

gboolean service_send_change(gpointer data)
{
id = 0;
printf("signal aaaaaaaaaaaaa%d\n", id);
return true;
}

gboolean service_send_changed(gpointer data)
{
id = 0;
printf("signal iiiiiiiiiiiis %d\n", id);
return true;
}

int main(int argc, char* argv[])
{
GMainLoop* loop;
if(g_thread_supported() == 0)
g_thread_init(NULL);
g_print("g_main_loop_new\n");
loop = g_main_loop_new(NULL, FALSE);
//Ôö¼ÓÒ»¸ö¶¨Ê±Æ÷£¬100ºÁÃëÔËÐÐÒ»´Îcallback
id = g_timeout_add(500,service_send_changed,NULL);
g_timeout_add(100, service_send_change,NULL);
g_print("g_main_loop_run\n");
g_main_loop_run(loop);
g_print("g_main_loop_unref\n");
g_main_loop_unref(loop);
return 0;
}
编译:

Makefile:

</pre><pre name="code" class="cpp">CC=gcc
.PHONY:all
all:test timer watch1
test:
$(CC) test.c -pthread -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -pthread -lgthread-2.0 -lglib-2.0 -o test
timer:
$(CC) timer.c -pthread -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -pthread -lgthread-2.0 -lglib-2.0 -o timer
watch1:
$(CC) watch1.c -pthread -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -pthread -lgthread-2.0 -lglib-2.0 -o watch1

clean:
rm test timer watch1