标签:
#ifndef THREAD_UTIL_H #define THREAD_UTIL_H #include <pthread.h> namespace spider { class AutoLock { pthread_mutex_t * _lock; public: AutoLock(pthread_mutex_t * lock) { _lock = lock; pthread_mutex_lock(_lock); } ~AutoLock() { pthread_mutex_unlock(_lock); } }; class RWLock { pthread_rwlock_t _lock; public: RWLock() { pthread_rwlock_init(&_lock, NULL); } int read() { return pthread_rwlock_rdlock(&_lock); } int write() { return pthread_rwlock_wrlock(&_lock); } int unlock() { return pthread_rwlock_unlock(&_lock); } }; class AutoRead { RWLock * _lock; public: AutoRead(RWLock * p) { _lock = p; _lock->read(); } ~AutoRead() { _lock->unlock(); } }; class AutoWrite { RWLock * _lock; public: AutoWrite(RWLock * p) { _lock = p; _lock->write(); } ~AutoWrite() { _lock->unlock(); } }; } #endif // THREAD_UTIL_H /* vim: set ts=4 sw=4 sts=4 tw=100 */ c++多线程之读写锁 pthread是POSIX threads的简称,是POSIX的线程标准 pthread读写锁把对共享资源的访问分为读者和写者,读者只对共享资源进行读访问,写者只对共享资源进行写操作。 在互斥机制,读者和写者都需要独立独占互斥量以独占共享资源, 在读写锁机制下,允许同时有多个读者访问共享资源,只有写者才需要独占资源。 相比互斥机制,读写机制由于允许多个读者同时访问共享资源,进一步提高了多线程的并发度。 http://www.th7.cn/Program/cp/201405/195894.shtml
标签:
原文地址:http://www.cnblogs.com/i80386/p/4478021.html