linux初探

首页

应用服务器

Linux技巧

中文文档

Linux初级

服务器源代码

命令详解

Linux技术应用

Linux安全应用

Linux业界新闻

UniX技术文章

Linux编程与内核

Linux数据库

Linux服务器

Linux安装指导

Linux论坛


首页>>Linux编程与内核>>

热门文章

·C/C++中多维数组指针作为函数
·教你如何使用 C++Builder 制
·C++ Builder中保持控件的位置
·C++Builder中动态更改自定义
·拓展网页技术之C++在网页设计
·C++Builder创建基于Internet
·C++Builder在WIN2000环境下编
·用C++ Builder为计算机增加启
·C++/VC++ 语言编程的疑难问题
·C/C++语言void及void指针深层

推荐文章

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

相关文章:

·Linux shell 脚本
·shell里面调用几个GUI程序,请高手赐教!
·嵌入式Linux系统之初体验
·Linux内核编译步骤(新手)方案
·Linux操作系统的内核重入的分析
·Linux设备驱动编程中断处理
·寻找附件的其他部分
·请教 redhat linux as4(2.6.9-22.ELsmp) 内核升级
·陈皓力作-《跟我一起写 Makefile》

Copyright@2005 www.linuxGoo.com All Right Reserved