监视器对象设计模式使并发方法的执行同步化,以确保任一时刻仅有一个方法在对象内运行。别名线程安全被动对象。
问题场景:应用程序包含被多个线程并发调用的对象。这些方法通常修改其对象的内部状态。为了并发线程内正确执行,有必要对对象的访问进行同步和调度。如果客户机必须显示的获取和释放底层同步机制,如信号、互斥或条件变量。那么并发应用程序更难编程。因此,对象应该负责确保它们需要同步的任何方法被透明的串行化。
代码示例:#include#include #include #include #include #include using namespace std; class Mutex { public: Mutex() { pthread_mutex_init(&_lock, NULL); } virtual ~Mutex() { pthread_mutex_destroy(&_lock); } void Lock() { pthread_mutex_lock(&_lock); } void Unlock() { pthread_mutex_unlock(&_lock); } pthread_mutex_t* GetLock() { return &_lock; } private: pthread_mutex_t _lock; }; class TreadCond { public: TreadCond() { pthread_cond_init(&m_cond, NULL); } virtual ~TreadCond() { pthread_cond_destroy(&m_cond); } void CondNotify() { pthread_cond_signal(&m_cond); } void CondWait(pthread_mutex_t* lock) { pthread_cond_wait(&m_cond, lock); } private: pthread_cond_t m_cond; }; class ScopedLock { public: ScopedLock( Mutex& mutex_obj ) : _mutex_obj(mutex_obj) { _mutex_obj.Lock(); } ~ScopedLock() { _mutex_obj.Unlock(); } private: Mutex& _mutex_obj; }; class MessageQueue { enum {MAX_SIZE = 100,}; public: MessageQueue(int size = MAX_SIZE): m_size(size), m_mesageCount(0) { } ~MessageQueue() { delete m_array; } void put(int value) { ScopedLock lock(m_mutex); while(i_full()) { m_notFullCond.CondWait(m_mutex.GetLock()); cout<<"full"<