ACE中的Thread Mutex在linux下的使用

ACE庫中專門對線程同步提供了兩個類,一個是ACE_Thread_Mutex另一個是ACE_REcursive_Thread_Mutex。 在我看 來,在linux下進行線程同步,不要使用ACE_Thread_Mutex,用ACE_REcursive_Thread_Mutex就可以了。原因很 簡單,因爲ACE_Thread_Mutex不支持線程重入。一旦重入(同一個線程調用兩次ACE_Thread_Mutex::acquire)這個線 程就死鎖了。

要搞清楚這個問題,我們需要搞清楚操作系統是如何實現線程鎖的。Windows下很簡單,用CRITICAL_SECTION實現。 CRITICAL_SECTION支持重入,所以Windows下的線程同步用ACE_Thread_Mutex或者 ACE_REcursive_Thread_Mutex都是一樣的。而linux下不同,是用posix thread 庫實現的。pthread 的mutex分爲三種類型,fast,recursive,error checking,當線程調用pthread_mutex_lock時,如果是線程重入這把鎖,則:

“fast”鎖 掛起當前線程.
“resursive”鎖 成功並立刻返回當前被鎖定的次數
“error checking” 鎖立刻返回EDEADLK

顯然ACE_Thread_Mutex是用fast方式實現的。

我有多個平臺 (Window,AIX ,Solaris,hp-ux,Linux)的C++多線程程序的開發經驗,但是一直都沒有想清楚一個不可重入的線程鎖有什麼用,用這樣的鎖用起來太不方便,要很小心了, 一不小心就會死鎖。所以一般情況下都需要手工寫代碼將它封裝成一個可以重入的鎖。ACE中也提供了這樣一個封裝,用mutex和cond實現的,代碼如 下:

ACE_OS::recursive_mutex_lock (ACE_recursive_thread_mutex_t *m)
{
#if defined (ACE_HAS_THREADS)
#if defined (ACE_HAS_RECURSIVE_MUTEXES)
return ACE_OS::thread_mutex_lock (m);
#else
ACE_thread_t t_id = ACE_OS::thr_self ();
int result = 0;

// Acquire the guard.
if (ACE_OS::thread_mutex_lock (&m->nesting_mutex_) == -1)
result = -1;
else
{
// If there’s no contention, just grab the lock immediately
// (since this is the common case we’ll optimize for it).
if (m->nesting_level_ == 0)
m->owner_id_ = t_id;
// If we already own the lock, then increment the nesting level
// and return.
else if (ACE_OS::thr_equal (t_id, m->owner_id_) == 0)
{
// Wait until the nesting level has dropped to zero, at
// which point we can acquire the lock.
while (m->nesting_level_ > 0)
ACE_OS::cond_wait (&m->lock_available_,
&m->nesting_mutex_);

// At this point the nesting_mutex_ is held…
m->owner_id_ = t_id;
}

// At this point, we can safely increment the nesting_level_ no
// matter how we got here!
m->nesting_level_++;
}

{
// Save/restore errno.
ACE_Errno_Guard error (errno);
ACE_OS::thread_mutex_unlock (&m->nesting_mutex_);
}
return result;
#endif /* ACE_HAS_RECURSIVE_MUTEXES */
#else
ACE_UNUSED_ARG (m);
ACE_NOTSUP_RETURN (-1);
#endif /* ACE_HAS_THREADS */
}

這個封裝是用在那些posix thread庫不支持recursive mutex的平臺上的。如果posix thread支持recursive ,那麼直接用pthread_mutex_lock就可以了。所以我的結論是:在ACE環境下,直接使用ACE_REcursive_Thread_Mutex,忘記 ACE_Thread_Mutex的存在。

轉存自:http://hi.baidu.com/%CF%E6%BD%AD%B1%DF%B5%C4%B4%AC%B7%F2/blog/item/2b81a9117a192b7eca80c41b.html

發佈了9 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章