您的位置:首页 > 运维架构

pthread_cleanup_push、pthread_cleanup_pop必须成对使用,否则编译不过!

2014-05-13 18:22 375 查看
http://blog.csdn.net/openxmpp/article/details/8583194
http://bbs.chinaunix.net/thread-1949867-1-1.html
pthread_cleanup_push注册一个回调函数;回调执行的可能位置:1、线程退出;2、响应cancel;3、pthread_cleanup_pop(1)
-----如果线程被kill,并不一定会执行。


pthread的建议是,如果一个函数是阻塞的,那么你必须在这个函数前后建立取消点,比如:

printf("thread sleep\n");

pthread_testcancel();

sleep(10);

pthread_testcancel();

printf("thread wake...\n");

这样,就添加了两个取消掉。在执行到pthread_testcancel的位置时,线程才可能响应cancel退出进程。

额外的知识:pthread_setcancelstate

对于cancel信号,线程有两种方法: 忽略,和响应。默认是响应

接收到cancel信号,线程有两种处理类型: 立即响应 和 延迟响应(在最近的取消点响应),默认是延迟响应

举例:freediameter中

static int core_state_wait(enum core_state waitstate)

{

int ret = 0;

CHECK_POSIX( pthread_mutex_lock( &core_mtx ));

pthread_cleanup_push( fd_cleanup_mutex, &core_mtx ); ----------解锁

while (waitstate > core_state) {

CHECK_POSIX_DO(ret = pthread_cond_wait(&core_cnd, &core_mtx), break);

}

pthread_cleanup_pop( 0 ); -------- 0,则不执行fd_cleanup_mutex;1,执行fd_cleanup_mutex。

CHECK_POSIX( pthread_mutex_unlock( &core_mtx ));

return ret;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: