Boostスレッド同期メカニズム

7880 ワード

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 the Lockable concept to add support for timeouts when trying to acquire the lock.
The SharedLockable concept is a refinement of the TimedLockable concept that allows forshared ownership as well asexclusive ownership. 
The UpgradeLockable concept is a refinement of the SharedLockable concept that allows forupgradable ownership as well asshared ownership andexclusive ownership.
2.Mutexオブジェクト
#include #include
... boost::mutexは、排他的アクセスの反発対象をサポートする.
boost::try_mutex boost::mutex, 。 boost::timed_mutex 。 boost::recursive_mutex 。 boost::recursive_timed_mutex の .boost::shared_mutex な オブジェクト.
3.ロック
#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(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 to wait() : 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::condition_variable cond;
boost::mutex mut;
bool data_ready;

void process_data();

void wait_for_data_to_process()
{
    boost::unique_lock<: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<:mutex>.
6.Barriers(レベル)
した のスレッドを ポイントで できます.
#include 

class barrier
{
public:
    barrier(unsigned int count);
    ~barrier();

    bool wait();
};

7.  Futures
のデータを するために され、これらのデータは1つ のスレッドで される があります.