【发布时间】:2014-01-30 12:44:08
【问题描述】:
在pthreads 中,我可以使用清理句柄函数并将它们放在带有pthread_cleanup_push() 的堆栈上。
是否有与 boost 线程类似的概念?
【问题讨论】:
标签: boost pthreads boost-thread
在pthreads 中,我可以使用清理句柄函数并将它们放在带有pthread_cleanup_push() 的堆栈上。
是否有与 boost 线程类似的概念?
【问题讨论】:
标签: boost pthreads boost-thread
不,但您可以通过将线程函数包装到另一个函数中来模仿它,该函数调用您的函数,然后调用您的清理处理程序。
另一种解决方案是将您需要的所有内容添加到您的清理处理程序中,并将其放入线程本地存储的析构函数中。但是,如果您必须为所有线程调用该清理处理程序,则必须确保确实使用了这样的线程局部变量,并且归结为包装您的线程函数。
如果你想替换 pthread_cleanup_push() 和 pop() 调用,我会选择构造函数和析构函数,所以
void roll_back( void* i );
{
do_rollback( *(int*)i );
}
void thread()
{
int roll_back_arg = 4;
pthread_cleanup_push( &roll_back, &roll_back_arg );
// transaction
pthread_clean_up_pop( 0 );
}
可以翻译成:
struct roll_back_guard
{
roll_back_guard( int arg ) : arg_( arg ), commit_( false ) {}
void commit() {
commit_ = true;
}
~roll_back_guard() {
if ( !commit_ )
do_rollback( arg_ );
}
};
void thread()
{
roll_back_guard guard( 4 );
// transaction
guard.commit();
}
通常这种模式称为作用域守卫。
【讨论】:
pthread_cleanup_push() 和pthread_cleanup_pop() 包围线程的主代码。