2014年01月14日 星期二 10:34
APR util提供了方便好用的thread pool模块,这对于实现多线程并发网络服务器非常有意义,thread pool帮助我们管理线程池,我们只需要实现业务逻辑即可。
代码示例如下:
#include <stdio.h> #include <apr.h> #include <apr_pools.h> #include <apr_errno.h> #include <apr_strings.h> #include <apr_thread_pool.h> void apr_err(const char *s, apr_status_t rv) { char buf[120]; fprintf(stderr, "%s: %s (%d)\n", s, apr_strerror(rv, buf, sizeof buf), rv); } void *thread_func(apr_thread_t *thd,void *arg) { long i=(long)arg; for(int j=0;j<20;j++) { printf("task %d => %d\n",i,j); apr_sleep(300000); } return NULL; } int main(int argc,char **argv) { apr_initialize(); apr_pool_t *pool; apr_pool_create(&pool,NULL); apr_status_t st; apr_thread_pool_t *tpl; st=apr_thread_pool_create(&tpl,8,128,pool); apr_size_t n; apr_thread_pool_schedule(tpl,thread_func, (void *)100000,5000000,NULL); for(long i=0;i<30;i++) { apr_thread_pool_push(tpl,thread_func, (void *)i,APR_THREAD_TASK_PRIORITY_NORMAL,NULL); apr_sleep(50000); } for(long i=0;i<20;i++) { n=apr_thread_pool_idle_count(tpl); printf("idle thread : %d\t\t",n); n=apr_thread_pool_busy_count(tpl); printf("busy thread : %d\t\t",n); n=apr_thread_pool_threads_count(tpl); printf("total thread : %d\n",n); apr_sleep(1000000); } apr_thread_pool_destroy(tpl); apr_pool_destroy(pool); apr_terminate(); return 0; }
参考资料:
http://apr.apache.org/docs/apr-util/1.3/group___a_p_r___util___t_p.html
Zeuux © 2024
京ICP备05028076号