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()執行完後會自行結束。

沒有留言: