gcc 4.7.2
c89
apr utility 1.4你好,
我正在使用线程池来启动线程。但是,我看不到任何允许我等待线程加入的apr函数。
代码sippet,删除了所有错误检查和不必要的部分:
int main(void)
{
/* Initialize apr internal structures */
apr_initialize();
/* Create memory pool */
rv = apr_pool_create(&mem_pool, NULL);
/* Create thread pool */
memset(&buf, 0, sizeof buf);
rv = apr_thread_pool_create(&thd_pool,
init_threads,
max_threads,
mem_pool);
/* Process the number of jobs */
#define NUMBER_JOBS 1
for(i = 0; i < NUMBER_JOBS; i++) {
rv = apr_thread_pool_schedule(thd_pool,
timeout_duration,
(void*)channel,
(apr_interval_time_t)flash_timeout,
NULL);
}
/*
* Join all threads here
*/
/* Destroy resources */
apr_thread_pool_destroy(thd_pool);
apr_pool_destroy(mem_pool);
apr_terminate();
return 0;
error:
apr_thread_pool_destroy(thd_pool);
apr_pool_destroy(mem_pool);
apr_terminate();
return 1;
}
void* timeout_duration(apr_thread_t *thd, void *data)
{
channel_t *channel = (channel_t*)data;
LOG_DEBUG("Channel timeout notification [ %zu ]", channel->id);
}我看不到任何连接线程的apr实用函数。
但是,我确实找到了这个函数apr_thread_join(apr_status_t *retval, apr_thread_t *thd),它以apr_thread_t作为参数。
函数timeout_duration接受一个apr_thread_t,但是如果我需要用它来连接,我怎么能把它传递回去呢?
这只是一个附注问题。有没有使用apr的示例项目,我可以参考。文档非常有限。
非常感谢您的建议,
发布于 2013-02-03 16:12:47
Short anser
你不需要加入线程池中的线程。当您调用apr_thread_pool_destroy时,该函数将会阻塞,直到所有线程都完成了当前任务。
首先回答你的最后一个问题:我没有找到一个例子,但是libapr和libapr-util是开源的,你可以阅读源代码,这是我所做的:(我检查了SVN-trunk here版本1441871)
Long answer
有趣的文件:
首先签入apr_thread_pool.c:394。在这里我们找到了apr_thread_pool_destroy的实现。我们可以看到它使用三个参数调用一个名为apr_pool_cleanup_run的函数,一个是池存储,一个是线程池上下文,最后一个是指向函数thread_pool_cleanup的函数指针。
如果我们遵循apr_pool_cleanup_run,我们将到达apr_pools.c:2453,并看到apr_pool_cleanup_kill被调用。阅读最后一个函数向我们展示,在这里,在元素(线程)上的几个循环中,通过调用cleanup_fn- function -argument (我们将在后面看到的内容)来清理。
现在回到函数apr_pool_cleanup_run,有一个对cleanup_fn的最后调用。
真正的动作是传递给apr_pool_cleanup_run的函数指针。所以,如果我们回到apr_thread_pool.c:329,我们找到了函数thread_pool_cleanup。
其中,上下文变量terminated被设置为1,然后该函数处于“休眠”状态,直到_myself->thd_cnt变为0。
搜索terminated的用法,我们发现当terminated不是0时,thread_pool_func正在退出其循环。事实证明,thread_pool_func是线程池中的每个线程都在使用的函数。在循环中,任务被获取并执行。当循环终止时(因为terminated变为1),将执行以下代码:
/* idle thread been asked to stop, will be joined */
--me->thd_cnt;这最终将导致thd_cnt==0,这是thread_pool_cleanup中循环的终止条件。
当您调用apr_thread_pool_destroy时,所有线程都会在函数返回之前完全停止。
https://stackoverflow.com/questions/14641792
复制相似问题