複数のmutexに対するlock_guardが欲しいと思ったので書いてみた。動くかどうかテストしていない。
template < int I > struct unlock { template < typename T > void apply( T & t ) { unlock< I - 1 >::apply( t ) ; std::get<I>(t)->unlock() ; } } ; template <> struct unlock<0> { template < typename T > void apply( T & t ) { std::get<0>(t)->unlock() ; } } ; template < typename ... Types > class multiple_lock_guard { public : typedef std::tuple< Types *... > type ; multiple_lock_guard( Types & ... args ) : m( &args... ) { std::lock( args... ) ; } ~multiple_lock_guard() { unlock< sizeof...(Types) - 1 >::apply( m ) ; } multiple_lock_guard( multiple_lock_guard const & ) = delete ; multiple_lock_guard & operator = ( multiple_lock_guard const & ) = delete ; private : type m ; } ;
こういうふうに使う。
std::mutex m1, m2, m3 ; int main() { multiple_lock_guard< std::mutex, std::mutex, std::mutex > guard( m1, m2, m3 ) ; }
追記、コピーコンストラクタ―と代入演算子のdeleteを忘れていた。
No comments:
Post a Comment
You can use some HTML elements, such as <b>, <i>, <a>, also, some characters need to be entity referenced such as <, > and & Your comment may need to be confirmed by blog author. Your comment will be published under GFDL 1.3 or later license with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.