顯示具有 Glib 標籤的文章。 顯示所有文章
顯示具有 Glib 標籤的文章。 顯示所有文章

2009年11月24日 星期二

Glib(2) MainLoop, timeout and thread

這個範例展示如何使用多線程,包含timeout function及thread function。

thread.c

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

#define G_THREADS_ENABLED //use multi-thread safe

gboolean TimerFunc (gpointer data)
{
printf ("Timeout: %s\n\n",(char *)data);
return TRUE;
}

gpointer ThreadFunc (gpointer data)
{
int i;
for (i = 0; i < 10; i++)
{
g_print("Thread: %s\n", (char *)data);
g_usleep(500000);
}
return NULL;
}

int main ()
{
GMainLoop *loop;

/* Either the thread system is initialized or, if no thread system is available in GLib , the program will abort */
if (!g_thread_supported ())
{
g_thread_init (NULL);
}

/* Creates a new GMainLoop structure. */
loop = g_main_loop_new (NULL,FALSE);

/* This function creates a new thread with the default priority.
GThread * g_thread_create(GThreadFunc func, gpointer data,
gboolean joinable, GError **error); */
g_thread_create(ThreadFunc, "Running", FALSE, NULL);

/* Sets a function to be called at regular intervals.
guint g_timeout_add(guint interval, GSourceFunc function, gpointer data);*/
g_timeout_add(2000, TimerFunc, ".......");

/* Runs a main loop until g_main_loop_quit() is called on the loop. */
g_main_loop_run(loop);

return 0;
}


這次compile 要再加上 gthread-2.0 library,執行的結果如下:

sh-3.2# ./thread
Thread: Running
Thread: Running
Thread: Running
Thread: Running
Timeout: .......

Thread: Running
Thread: Running
Thread: Running
Thread: Running
Timeout: .......

Thread: Running
Thread: Running
Timeout: .......

Timeout: .......

Timeout: .......

ThreadFunc()執行完後會自行結束。

2009年11月20日 星期五

Glib (1) Key-value file parser

Glib中有個功能,Key-value file parser 是用來讀取你一個設定檔,如一般常看到的.ini or .conf ,運用glib 可以很容易分析出所設定的參數。用一個小程式來了解如何運用這項功能:
demo file: keyfile.c myconf.ini


keyfile.c

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

typedef struct
{
gchar **prod;
gint *price;
} GOODS;

int main()
{
GOODS *conf;
GKeyFile *keyfile;
GKeyFileFlags flags;
GError *error = NULL;
int channel;
double freq;
gsize length;
int i;

// Create a new GKeyFile object and a bitwise list of flags.
keyfile = g_key_file_new();
flags = G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS;

// Load the GKeyFile from keyfile.conf or return.
if (!g_key_file_load_from_file (keyfile, "myconf.ini", flags, &error))
return 0;

printf("[doc]\n");
printf("value: %d\n", g_key_file_get_integer(keyfile, "doc", "value", NULL));
printf("version: %s\n", g_key_file_get_string(keyfile, "doc", "version", NULL));

printf("\n[TV]\n");
if (g_key_file_get_boolean(keyfile, "tv", "on", NULL))
printf("TV: true\n");
else
printf("TV: true\n");
channel=g_key_file_get_integer(keyfile, "tv", "channel", NULL);
freq=g_key_file_get_double(keyfile, "tv", "Hz", NULL);
printf("TV: %d\n", channel);
printf("TV: %f\n",freq);

/* Create a new Settings object. If you are using GTK+ 2.8 or below, you should use g_new() or g_malloc() instead! */
conf = g_slice_new (GOODS);

conf->prod = g_key_file_get_string_list(keyfile, "LIST","prod_list", &length, NULL);
conf->price= g_key_file_get_integer_list(keyfile, "LIST","price_list", &length, NULL);

printf("\n[LIST]\n");
printf("name: ");
for(i=0;i printf("%s ",conf->prod[i]);

printf("\nprice: ");
for(i=0;i printf("%d ",conf->price[i]);

printf("\n");

return 0;
}



myconf.ini



# This is a example

[doc]
value=66
version=2.6.17

[tv]
on=yes
channel=23
Hz=59.6

[LIST]
prod_list=book;coffee;pen
price_list=23;54;3


接下來編譯:


[root@ecken02 glib]# arm-linux-gcc -Wall -static `arm-linux-pkg-config --cflags --libs glib-2.0` -o keyfile keyfile.c -lglib-2.0 -liconv -lintl

移到版子上執行
sh-3.2# ./keyfile
[doc]
value: 66
version: 2.6.17

[TV]
TV: true
TV: 23
TV: 59.600000

[LIST]
name: book coffee pen
price: 23 54 3
sh-3.2#


它已經將設定檔的值讀出來了,不過感覺執行的速度有點慢....

sh-3.2# ls -l
-rwxrw-r-- 1 root root 152 Nov 9 2009 Makefile
-rwxr-xr-x 1 root root 2304376 Nov 23 2009 keyfile
-rwxrw-r-- 1 root root 1641 Nov 9 2009 keyfile.c
-rwxrw-r-- 1 root root 136 Nov 9 2009 myconf.ini
sh-3.2#

天啊 !! 想不到執行檔要2.3M,真是不符合軟體短小精幹的要求。
再去掉不必要的symbol,

sh-3.2# ls -l
-rwxrw-r-- 1 root root 152 Nov 9 2009 Makefile
-rwxr-xr-x 1 root root 1363192 Nov 23 2009 keyfile
-rwxrw-r-- 1 root root 1641 Nov 9 2009 keyfile.c
-rwxrw-r-- 1 root root 136 Nov 9 2009 myconf.ini
sh-3.2#

還有1.3M,差不多就只能這樣了。

2009年11月19日 星期四

Porting Glib to ARM

Glib 是一種低階的函式庫,創建 GDK 和 GTK 應用程式時該函式庫可提供許多有用的定義和函式。
它全部是用C語言構成的,當要大量使用資料結構或演算法時,它真的是一個好的library,雖然不玩GTK,不過glib的功能可以簡化我的程式碼,不用寫的哩哩摳摳一大串,現在先從它的README看一下它的功能:

GLib Core Application Support
The Main Event Loop — manages all available sources of events
Threads — thread abstraction; including threads, different mutexes, conditions and thread private data
Thread Pools — pools of threads to execute work concurrently
Asynchronous Queues — asynchronous communication between threads
Dynamic Loading of Modules — portable method for dynamically loading 'plug-ins'
Memory Allocation — general memory-handling
IO Channels — portable support for using files, pipes and sockets
Error Reporting — a system for reporting errors
Message Output and Debugging Functions — functions to output messages and help debug applications
Message Logging — versatile support for logging messages with different levels of importance

GLib Utilities
String Utility Functions — various string-related functions
Character Set Conversion — convert strings between different character sets using iconv()
Unicode Manipulation — functions operating on Unicode characters and UTF-8 strings
Base64 Encoding — encodes and decodes data in Base64 format
Data Checksums — Computes the checksum for data
Internationalization — gettext support macros
Date and Time Functions — calendrical calculations and miscellaneous time stuff
Random Numbers — pseudo-random number generator
Hook Functions — support for manipulating lists of hook functions
Miscellaneous Utility Functions — a selection of portable utility functions
Lexical Scanner — a general purpose lexical scanner
Automatic String Completion — support for automatic completion using a group of target strings
Timers — keep track of elapsed time
Spawning Processes — process launching
File Utilities — various file-related functions
URI Functions — URI Functions
Hostname Utilities — Internet hostname utilities
Shell-related Utilities — shell-like commandline handling
Commandline option parser — parses commandline options
Glob-style pattern matching — matches strings against patterns containing '*' (wildcard) and '?' (joker)
Perl-compatible regular expressions — matches strings against regular expressions
Simple XML Subset Parser — parses a subset of XML
Key-value file parser — parses .ini-like config files
Bookmark file parser — parses files containing bookmarks
Testing — a test framework
Windows Compatibility Functions — UNIX emulation on Windows

GLib Data Types
Memory Slices — efficient way to allocate groups of equal-sized chunks of memory
Memory Chunks — deprecated way to allocate groups of equal-sized chunks of memory
Doubly-Linked Lists — linked lists containing integer values or pointers to data, with the ability to iterate over the list in both directions
Singly-Linked Lists — linked lists containing integer values or pointers to data, limited to iterating over the list in one direction
Double-ended Queues — double-ended queue data structure
Sequences — scalable lists
Trash Stacks — maintain a stack of unused allocated memory chunks
Hash Tables — associations between keys and values so that given a key the value can be found quickly
Strings — text buffers which grow automatically as text is added
String Chunks — efficient storage of groups of strings
Arrays — arrays of arbitrary elements which grow automatically as elements are added
Pointer Arrays — arrays of pointers to any type of data, which grow automatically as new elements are added
Byte Arrays — arrays of bytes, which grow automatically as elements are added
Balanced Binary Trees — a sorted collection of key/value pairs optimized for searching and traversing in order
N-ary Trees — trees of data with any number of branches
Quarks — a 2-way association between a string and a unique integer identifier
Keyed Data Lists — lists of data elements which are accessible by a string or GQuark identifier
Datasets — associate groups of data elements with particular memory locations
Relations and Tuples — tables of data which can be indexed on any number of fields
Caches — caches allow sharing of complex data structures to save resources
Memory Allocators — deprecated way to allocate chunks of memory for GList, GSList and GNode

從它文件中,可以看到它提供很多的功能,為了要了解它提供的一些功能,先把它移植到ARM,順便再做一些範例。 (PS:唉,又是ARM,誰叫我是做embedded的呢。不過其實一些功能已經在PC上測過了,真的還蠻方便的,不過一直沒實做到ARM上。)

CPU:ARM9
toolchain: GCC 4.2.1
glib dependence: libiconv , gettext

gettext-0.16.1.tar.gz
[root@ecken02 gettext-0.16.1]# ./configure --host=arm-linux --prefix=/usr/local/arm_linux_4.2/arm-linux
[root@ecken02 gettext-0.16.1]# make
[root@ecken02 gettext-0.16.1]# make install

libiconv-1.13.1.tar.gz
[root@ecken02 libiconv-1.13.1]# ./configure --host=arm-linux --prefix=/usr/local/arm_linux_4.2/arm-linux
[root@ecken02 libiconv-1.13.1]# make
[root@ecken02 libiconv-1.13.1]# make install

glib-2.20.5.tar.gz
[root@ecken02 glib-2.20.5]# ./configure --host=arm-linux --prefix=/usr/local/arm_linux_4.2/arm-linux/ --enable-static --disable-selinux --cache-file=arm-linux.cache
[root@ecken02 glib-2.20.5]# make
[root@ecken02 glib-2.20.5]# make install

編譯glib之前先設好一些參數,其原因absurd在他的博客已有說明
#cat arm-linux.cache
ac_cv_type_long_long=yes
glib_cv_stack_grows=no
glib_cv_uscore=no
ac_cv_func_posix_getpwuid_r=yes
ac_cv_func_posix_getgrgid_r=yes

compile時會有一個錯誤,
giounix.c:185: error: 'SSIZE_MAX' undeclared
將#include <bits/posix1_lim.h> 加到giounix.c 即可


至此應該已經將glib library加入系統中了。接下來運用它提供的function來做些範例。