089 - 问,scope lock,shared lock,upgrade lock

089 - 问,scope lock,shared lock,upgrade lock

一直使用boost的scope_lock,今天想来看下boost thread库的各种功能,看到还有shared_lock / upgrade_lock。学习一下。

Mutex

089 - 问,scope lock,shared lock,upgrade lock_第1张图片

Lock

089 - 问,scope lock,shared lock,upgrade lock_第2张图片

总结

独占锁(写锁)

Lock_guard(不能与timed_mutex配合)

Unique_lock

boost::lock_guard<>和boost::unique_lock<>的区别

boost::mutex  m;

void foo( )

{

        boost::lock_guard<boost::mutex> lk( m );

        process( data );

};

lock_guard只能像上面这样使用,而unique_lock允许设置超时,推迟锁定lock以及在对象销毁之前unlock。

{

        boost::unique_lock<boost::mutex> lk( m );

        process( data );

        lk.unlock( );

        // do other thing

};

读锁

Shared_lock

锁的升级

boost::shared_mutex _access;

void reader()

{

  boost::shared_lock< boost::shared_mutex > lock(_access);

  // do work here, without anyone having exclusive access

}

void conditional_writer()

{

  boost::upgrade_lock< boost::shared_mutex > lock(_access);

  // do work here, without anyone having exclusive access

  if (something) {

  boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);

  // do work here, but now you have exclusive access

  }

  // do more work here, without anyone having exclusive access

}

void unconditional_writer()

{

  boost::unique_lock< boost::shared_mutex > lock(lock);

  // do work here, with exclusive access

}

参考资料

http://www.boost.org/doc/libs/1_45_0/doc/html/thread/synchronization.html#thread.synchronization.locks

http://www.boost.org/doc/libs/1_45_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.try_mutex

http://blog.csdn.net/hbhhww/article/details/7416170

你可能感兴趣的:(089 - 问,scope lock,shared lock,upgrade lock)