如果每当一个请求到达就创建一个新线程,开销是相当大的。在实际使用中,每个请求创建新线程的服务器在创建和销毁线程上花费的时间和消耗的系统资源甚至可能要比花在处理实际的用户请求的时间和资源要多得多。除了创建和销毁线程的开销之外,活动的线程也需要消耗系统资源。
线程池主要用来解决线程生命周期开销问题和资源不足问题。通过对多个任务重用线程,线程创建的开销就被分摊到了多个任务上了,而且由于在请求到达时线程已经存在,所以消除了线程创建所带来的延迟。这样,就可以立即为请求服务,使应用程序响应更快。另外,通过适当地调整线程池中的线程数目可以防止出现资源不足的情况。
一个比较简单的线程池至少应包含线程池管理器、工作线程、任务队列、任务接口等部分。glib提供了一套线程池的api,和pthread提供的那一套比起来方便了很多。
GThreadPool; GThreadPool* g_thread_pool_new (GFunc func, gpointer user_data, gint max_threads, gboolean exclusive, GError **error); void g_thread_pool_push (GThreadPool *pool, gpointer data, GError **error); void g_thread_pool_set_max_threads (GThreadPool *pool, gint max_threads, GError **error); gint g_thread_pool_get_max_threads (GThreadPool *pool); guint g_thread_pool_get_num_threads (GThreadPool *pool); guint g_thread_pool_unprocessed (GThreadPool *pool); void g_thread_pool_free (GThreadPool *pool, gboolean immediate, gboolean wait_); void g_thread_pool_set_max_unused_threads (gint max_threads); gint g_thread_pool_get_max_unused_threads (void); guint g_thread_pool_get_num_unused_threads (void); void g_thread_pool_stop_unused_threads (void); void g_thread_pool_set_sort_function (GThreadPool *pool, GCompareDataFunc func, gpointer user_data); void g_thread_pool_set_max_idle_time (guint interval); guint g_thread_pool_get_max_idle_time (void);
|
下面是一个使用线程池的例子
#include<glib.h> static void test_function(gpointer data, gpointer user_data) { int i; i = GPOINTER_TO_INT(data); g_print("test function %d\n",i); }
int main() { GThreadPool *pool = NULL; GError *error = NULL; //char data[10]="test";
int i,gthreadcount; GMutex *mutex; if ( g_thread_supported () ) printf("support g_thread\n"); g_thread_init (NULL); mutex = g_mutex_new(); pool = g_thread_pool_new(test_function,NULL,-1,FALSE,&error); if(pool == NULL) { g_print("can not create thread"); }
gthreadcount = g_thread_pool_get_num_threads(pool); g_print("gthread count is %d\n",gthreadcount);
g_mutex_lock(mutex); for(i = 0; i < 10 ; i++) { g_thread_pool_push(pool, (gpointer *)i , NULL); } g_mutex_unlock(mutex); // g_print("gthread count is %d\n",gthreadcount);
}
|
[root@localhost glib_test]# ./g_thread_pool
gthread count is 0
test function 1
test function 2
test function 3
test function 4
test function 5
test function 6
test function 7
test function 8
test function 9
gthread count is 1
测试程序循环从池中调用,可以看到实际上只创建了一个thread.
阅读(3063) | 评论(2) | 转发(0) |