發表文章

目前顯示的是 7月, 2010的文章

GLib 就是懶.GThreadPool 高效的執行緒池

開發複雜的程式時,執行緒(Thread)隨處可見,在高負載的應用程式中,就常會使用到多執行緒所構成的演算法,如 Apache 此類有許多流量及使用者操作的程式,就運用 Thread 做負載的分配。但是,每當 Thread 的建立和摧毀,會造成額外的系統資源開銷,若是有大量 Thread 增減將會造成程式效能不彰,所以最好的辦法便是回收並重新運用已經被建立的 Thread。因此,GLib 提供了 GThreadPool 的機制,可重復利用 Thread 以減少不必要的開銷。 這是一個使用 GThreadPool 的範例程式: void mythread(gpointer data, gpointer user_data) {     printf("%s\n", data);     printf("%s\n", user_data); } void main() {     gchar *data = "this is data";     gchar *user_data = "this is user_data";     GThreadPool *pool;     if(!g_thread_supported())          g_thread_init(NULL);      /* create thread pool */      pool = g_thread_pool_new(mythread, user_data, -1, FALSE, NULL);      if (pool==NULL)          printf("ERROR\n");     /* start three threads */      g_thread_pool_push(pool, data, NULL);      g_thread_pool_push(pool, data, NULL);      g_thread_pool_push(pool, data, NULL); }