Boost 线程同步机制

来源:互联网 发布:sql 修改字段中的内容 编辑:程序博客网 时间:2024/05/22 14:49

Boost.Thread.Synchronization

Boost 中,可以使用互斥(mutex)变量来进行同步, 通过锁(Lock)操作来获得mutex的所有权,通过解锁(Unlock)操作来让出所有权,而条件变量(condition_variable)则提供了一种机制用于一个线程等待另一个线程通知某个特定条件的状态变为真。

1. Mutex

Boost提供了recursive/non-recursive mutex(支持排他访问),  以及shared mutex(支持共享访问).

recursive mutex:  lock后,unlock之前,可再次lock.

non-recursive mutex: lock后,unlock之前,不可再次lock.

shared mutex: 可被多个访问者lock.

Mutex可以实现以下几种属性: 可加锁(排他访问)、加锁可超时、可被多个访问者加锁(共享访问)、加锁者可权限升级(将共享访问提升为排他访问)。

The Lockable concept models exclusive ownership.

The TimedLockable concept refines theLockable concept to add support for timeouts when trying to acquire the lock.

The SharedLockable concept is a refinement of theTimedLockable concept that allows forshared ownership as well asexclusive ownership

The UpgradeLockable concept is a refinement of theSharedLockable concept that allows forupgradable ownership as well asshared ownership andexclusive ownership.

2. Mutex对象

#include <boost/thread/mutex.hpp>
#include <boost/thread/shared_mutex.hpp>

...

boost::mutex 支持排他访问的互斥对象。

boost::try_mutex 等同于 boost::mutex, 用来兼容以前的版本。

boost::timed_mutex 支持超时的排他互斥对象。

boost::recursive_mutex 支持递归加锁的排他互斥对象。

boost::recursive_timed_mutex 支持递归和超时的排他互斥对象。

boost::shared_mutex 可共享的互斥对象。

3. Lock对象

#include <boost/thread/locks.hpp>

boost::lock_guard 是最简单的锁,构造时对传入的mutex加锁,析构时解锁。

boost::unique_lock  可以推迟lock(构造时指定defer_lock_t参数), 通过调用加锁函数显示lock: lock(), try_lock(), time_lock(), 可以调用unlock()解锁,或unique_lock对象析构时自动解锁。

boost::shared_lock  类似于unique_lock, 不同的是获得的是共享访问权限(前面获得的都是排他权限)。

boost::upgrade_lock  获得可升级的访问权限。

boost::upgrade_to_unique_lock 提升upgrade_lock权限,析构时upgrade_lock权限降级。

 explicit upgrade_to_unique_lock(upgrade_lock<Lockable>& m_);

4. Lock函数(全局函数)

lock(Lockable1,Lockable2,...)

lock(begin,end) // 将lockable对象(mutex)放到一个容器中

try_lock(Lockable1,Lockable2,...)

try_lock(begin,end)

用来对多个顺序不确定的mutex同时加锁,以避免死锁。

5. 条件变量 condition_variable

提供机制实现一个线程某个条件等待来自另一个线程的通知。

Notice that the lock is passed towait():wait will atomically add the thread to the set of threads waiting on the condition variable, and unlock the mutex.

boost::condition_variable

boost::condition_variable_any

通常的用法示例如下:

#include <boost/thread/condition_variable.hpp>boost::condition_variable cond;boost::mutex mut;bool data_ready;void process_data();void wait_for_data_to_process(){    boost::unique_lock<boost::mutex> lock(mut);    while(!data_ready)    {        cond.wait(lock);    }    process_data();}

condition_variable_any is more general, and will work with any kind of lock or mutex, whereas condition_variable requires that the lock passed to wait is an instance of boost::unique_lock<boost::mutex>.

6. Barriers (关卡)

可以使指定数量的线程在某个执行点同步。

#include <boost/thread/barrier.hpp>class barrier{public:    barrier(unsigned int count);    ~barrier();    bool wait();};

7.  Futures
用于同步未来的数据,这些数据可能被一个或多个线程产生。