2014-06-07 196 views
0

我想在scoped_lock中同時使用timed_mutex。我之前通過以下示例成功使用了scoped_lock,但現在我似乎無法找到解決方法,我也無法正確理解boost文檔。如何正確使用boost :: timed_mutex和scoped_lock

期望的行爲如下:嘗試獲取x時間的scoped_lock,如果成功返回true,否則返回false。

目前我有:

boost::timed_mutex _mutex; 
boost::timed_mutex::scoped_lock scoped_lock(_mutex, boost::get_system_time() + boost::posix_time::miliseconds(10)); 

然而,當我試圖找到(通過Boost文檔或實例)如果此scoped_lock中會返回一個布爾與否我覺得沒有什麼或找到真正不同的方式來做到這一點。

因此,我問哪個是正確的方法來做到這一點,它是如何正確工作,並可能指示如何正確「讀取」提升文檔。

UPDATE:

所以

boost::timed_mutex _mutex; 
boost::timed_mutex::scoped_lock scoped_lock(_mutex, boost::get_system_time() + boost::posix_time::miliseconds(10)); 

if(scoped_lock.owns_lock()) { 
    // exclusive code 
} 

將創建)一個互斥體,當我嘗試用scoped_lock.owns_lock(鎖定將嘗試在10毫秒獲取鎖(在這種情況下)和返回如果時間到了,並且沒有獲取鎖定,則返回false?

+0

這個問題可以幫助你: http://stackoverflow.com/questions/14200305/usage-of-boostunique-locktimed-lock –

回答

2

如果你看一下documentationboost::timed_mutex::scoped_lock僅僅是boost::unique_lock<timed_mutex>一個別名:

class timed_mutex: 
    boost::noncopyable 
{ 
public: 
    // ... 

    typedef unique_lock<timed_mutex> scoped_timed_lock; 
    typedef unspecified-type scoped_try_lock; 
    typedef scoped_timed_lock scoped_lock; 

    // ... 
}; 

現在檢查出documentationboost::unique_lock,它表明有兩種方法來確定,如果你擁有了鎖:

template<typename Lockable> 
class unique_lock 
{ 
public: 
    // ... 

    explicit operator bool() const noexcept; 
    bool owns_lock() const noexcept; 

    // ... 
}; 

因此,你可以做任何

if(scoped_lock) { 
    // we have the lock, yay! 
} 

if(scoped_lock.owns_lock()) { 
    // we have the lock, yay! 
} 

順便提及,unique_lock具有一個構造函數相對時間作爲計時::持續時間,其可以是或可以不是比使用絕對時間吸塵器。

編輯: 鑑於此代碼:

boost::timed_mutex _mutex; 
boost::timed_mutex::scoped_lock scoped_lock(_mutex, 
      boost::get_system_time() + boost::posix_time::miliseconds(10)); // <-- attempt to acquire mutex happens here! 

if(scoped_lock.owns_lock()) { 
    // exclusive code 
} 

獲取互斥鎖,發生在鎖構造時間的嘗試,而不是在時間owns_lock()被調用。是的,只有在您成功獲取互斥鎖後纔會執行獨佔代碼。我不確定你的意思是「返回false」 - 這段代碼不會返回任何東西。如果owns_lock()返回false,那麼您無法獲得互斥鎖並且無法運行獨佔代碼,並且您可以隨意將其傳遞給呼叫者。

+0

我已經更新了我的問題,以反映您的信息,並確保我已經很好理解了,請確認我是對的! –

+0

@ConradKurtz請參閱編輯。 –

相關問題