Chinaunix首页 | 论坛 | 博客
  • 博客访问: 697501
  • 博文数量: 260
  • 博客积分: 7033
  • 博客等级: 少将
  • 技术积分: 2633
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-13 23:15
文章分类

全部博文(260)

文章存档

2012年(2)

2011年(41)

2010年(78)

2009年(139)

我的朋友

分类: LINUX

2009-05-06 10:03:03

考虑到GConf在任何时候都有可能会读取磁盘上的配置文件。
那么,在磁盘或者是T卡作为磁盘的情况下,T卡的损坏可能会导致GConf读取不出来数据而阻塞进程。
 
这种情况是存在的么?
GConf有没有一种缓存机制。
可以在应用程序中请求gconfd-2把某个分支下的配置项一次性读入内存中做缓存??
 
 
使用GConfClient这个封装过的类来操作gconf可以实现缓存的效果:
A client-side cache for a specified list of directories you're interested in. You can "preload" entire directories into the cache, speeding things up even more.
 
应用程序中使用:
GConfClient* client = gconf_client_get_default();
来获取一个gconf的客户端,
查看gconf代码gconf-dbus-2.16.0+svnr641-r0/trunk/gconf/gconf-client.c,
 
gconf_client_get_default() -> engine = gconf_engine_get_default () -> client = lookup_client (engine);
 
gconf_client_get_default()首先调用gconf_engine_get_default()来获取一个engine。
这个gconf_engine_get_default()是在gconf-dbus-2.16.0+svnr641-r0/trunk/gconf/gconf-dbus.c中定义的,函数主要返回一个static型的engine指针:
static GConfEngine    *default_engine = NULL;
 
看来,每一个engine针对每个应用程序都是唯一的,而且不会重复生成。
 
获取到engine后,在使用此engine来获取一个client指针,而这个client指针是从一个Static类型的hash表指针中以engine为key来获取的。
 
static GHashTable * clients = NULL;
 
由于每个进程中engine是唯一的,所以使用gconf_client_get_default()获取到的client 应该也是唯一的。
 
经过打印每次调用gconf_client_get_default()获取的client指针的值,也证明了这一点,这些client指针的值都是一样的。
 
printf("client = 0x%p\n", client);
 
有关GHashTable的一个例子:
 
 
 
关于GConf加缓存的问题,开始的时候,想自己在下面封装一下GConfClient,使用hash算法把key/value缓存起来,后来继续看gconf的代码的时候,发现gconf已经聪明的实现了这个功能:
 
gconf_client_add_dir(client, dir, GCONF_CLIENT_PRELOAD_RECURSIVE, &error);
 
这里GCONF_CLIENT_PRELOAD_RECURSIVE是把dir目录下的所有文件都cache,调用这个函数的时候,如果dir下面的值比较多,可能会比较耗资源,但是为了要这个cache全目录的功能,使用这个函数肯定是没有问题的喽。
 
这里存在一个问题,就是add_dir后,如果对该dir下面的键值进行了修改,那么该键值就会从cache中删除,除非下次再读取这个键值的时候,才会将该键值对加入到cache.
 
应用程序退出时,要通知gconf保存当前的配置:
gconf_client_suggest_sync(client, &error);
 
 
 
虽然g_hash_table_foreach 提供了对表的链接操作,但是有的时候还想想像链表那样来一个一个的遍历,此时需要GHashTableIter。
下面的这个链接讲到了GHashTableIter的用法。
 
 

#include <glib.h>
int main(int argc, char *argv[])
{
    GHashTableIter iter;
    gpointer key, value;
    GHashTable *hashTable;

    hashTable = g_hash_table_new(g_str_hash, g_str_equal);

    g_hash_table_insert(hashTable, "justin", "justin's message!!");
    g_hash_table_insert(hashTable, "momor", "momor's message!!");
    g_hash_table_insert(hashTable, "caterpillar", "caterpillar's message!!");

    g_hash_table_iter_init (&iter, hashTable);

    while(g_hash_table_iter_next(&iter, &key, &value))
    {
        g_print("key\t: %s\nvalue\t: %s\n\n", key , value);
    }

    g_hash_table_destroy(hashTable);

    return 0;
}

输出结果:

key : justin
value : justin's message!!

key : caterpillar
value : caterpillar'
s

key : momor
value : momor

阅读(654) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~