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的存在。