glib学习笔记6 使用线程池

本文介绍线程池的基本原理及其在减少线程生命周期开销和避免资源不足问题中的作用。通过GLib提供的API实现线程池,并给出一个简单的示例程序,展示如何使用这些API来创建和管理线程池。
如果每当一个请求到达就创建一个新线程,开销是相当大的。在实际使用中,每个请求创建新线程的服务器在创建和销毁线程上花费的时间和消耗的系统资源甚至可能要比花在处理实际的用户请求的时间和资源要多得多。除了创建和销毁线程的开销之外,活动的线程也需要消耗系统资源。

线程池主要用来解决线程生命周期开销问题和资源不足问题。通过对多个任务重用线程,线程创建的开销就被分摊到了多个任务上了,而且由于 在请求到达时线程已经存在,所以消除了线程创建所带来的延迟。这样,就可以立即为请求服务,使应用程序响应更快。另外,通过适当地调整线程池中的线程数目 可以防止出现资源不足的情况。
一个比较简单的线程池至少应包含线程池管理器、工作线程、任务队列、任务接口等部分。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.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值