Ice中Monitor的使用

来源:互联网 发布:苹果电脑无法卸载软件 编辑:程序博客网 时间:2024/06/05 04:46
IceUtil::Monitor类
[cpp] view plain copy
  1. namespace IceUtil {  
  2. template <class T>  
  3. class Monitor {  
  4. public:  
  5.   void lock() const;  
  6.   void unlock() const;  
  7.   bool tryLock() const;  
  8.   void wait() const;  
  9.   bool timedWait(const Time&) const;  
  10.   void notify();  
  11.   void notifyAll();  
  12.   typedef LockT<Monitor<T> > Lock;  
  13.   typedef TryLockT<Monitor<T> > TryLock;  
  14. };  
  15. }  

1. 从代码可以看出,Monitor比Mutex(互斥体)多了wait/timedWait,notify/notifyAll操作。这样允许一个获得锁进入临界区的线程,能够自我挂起,让出临界区。

2.Monitor是个模板类,需要Mutex/RecMutex(递归互斥体)做为模板参数。

3.wait/timedWait在等待期间,会挂起线程,让出互斥体,等待被唤醒。

区别是:

timedWait(const Time&)会在时间到达后,自我唤醒,重新尝试获得锁;

wait()是等待被唤醒(其他线程调用notify()或者notifyAll()。

timedWait返回值:如果有另外的线程调用 notify 或 notifyAll,在发生超时之前唤醒挂起的线程,这个调用返回 true,监控器重被锁住,挂起的线程恢复执行。而如果发生超时,函数返回 false。

使用实例

[cpp] view plain copy
  1. template<class T> class Queue  
  2. public IceUtil::Monitor<IceUtil::Mutex> {  
  3. public:  
  4. void put(const T & item) {  
  5. IceUtil::Monitor<IceUtil::Mutex>::Lock lock(*this);  
  6. _q.push_back(item);  
  7.   notify();  
  8. }  
  9. T get() {  
  10.   IceUtil::Monitor<IceUtil::Mutex>::Lock lock(*this);  
  11.   while (_q.size() == 0)  
  12.     wait();  
  13.   T item = _q.front();  
  14.   _q.pop_front();  
  15.   return item;  
  16. }  
  17. private:  
  18.   list<T> _q;  
  19. };  

timedWait:时间到达后,尝试获取锁,但可能其他线程正在使用,当锁被释放时,才会真正得到,开始后续的执行。

[cpp] view plain copy
  1. .....  
  2. IceUtil::Monitor<IceUtil::Mutex>::Lock lock(*this);  
  3. if ( queue_.empty() || queue_.size() < buffer_size_ ) {  
  4.   IceUtil::Time time = IceUtil::Time::seconds( 10 );//等待10s  
  5.   timedWait(time);  
  6. }  
  7. ...  

补:

Mutex为简单互斥体:一个线程获得锁后,不能再尝试获得锁。

RecMutex为递归互斥体,一个线程可以多次尝试获得锁。

0 0