glib编程 (main event loop)

老鱼 posted @ 2010年1月31日 09:06 in c/cplusplus , 8498 阅读

最简单的例子

 

int main(int argc,char* argv)
{
	if (g_thread_supported() == 0)
		g_thread_init(NULL);

	g_print("g_main_loop_new\n");

	loop=g_main_loop_new(NULL,FALSE);
	
	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;
}

 

 

你会发现程序会在 g_main_loop_run函数阻塞,这就是glib main loop了,如果没有人通知它退出,它是不会退出的。
通知循环退出的函数是 g_main_loop_quit。
怎么通知呢?主线程被g_main_loop_run阻塞了,没办法运行quit。本来我准备开一个线 程,sleep一秒钟,然后调用g_main_loop_quit。不过一想我们都在学习高精尖武器了,还用土枪土炮干啥。使用glib的定时器吧~

 

 

#include <glib.h>


GMainLoop *loop;

gint counter = 10;
gboolean mycallback(gpointer arg)
{
	g_print(".");
	if(--counter==0){
		g_print("\n");
		//exiting lop
		g_main_loop_quit(loop);
		return FALSE;
		}
	return TRUE;
}

int main(int argc,char* argv)
{
	if (g_thread_supported() == 0)
		g_thread_init(NULL);

	g_print("g_main_loop_new\n");

	loop=g_main_loop_new(NULL,FALSE);

	g_timeout_add(100,mycallback,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;
}


 

 

.

一秒钟后,程 序正常退出了!

 

 

 

引:http://baicj.spaces.live.com/blog/cns!F60F8E193FAC08E4!410.entry

Avatar_small
linuxdog 说:
2014年4月27日 05:50

timer 在glib内部是否是一个线程实现的呢?

Avatar_small
deep cleaning 说:
2019年9月15日 15:00

Repair Services LLC is usually a professional clean-up services with Dubai. Barstools2u . com offers efficient in addition to perfectly cost cleaning services for villas, apartments in addition to buildings(Domestic/Residential) together with Office/ Manufacturing spaces. Also you can avail your maid services in Dubai. Super trusted and trained not professional maid with hour groundwork or steady maid services is what we've got to offer. Our deeply cleaning products and services for every day and practices are extremely in-demand services since recent years years. Had an event last nights? Leave this after gathering cleaning with us therefore you sit returning relaxed.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter