编程知识 cdmana.com

C + + mutexlock, mutexlockguard Implementation (Linux muduo Network Library Chen shuo)

MutexLockCatégorie:

class MutexLock:
{
public:
    MutexLock() {
        pthread_mutex_init(&m_mutex, NULL);
        holder_ = 0;
    }
    ~MutexLock() {
        assert(holder_ == 0);
        pthread_mutex_destroy(&m_mutex);
    }
    bool isLockedByThisThread() {
        return holder_ == CurrentThread::tid();
    }
    void assertLocked() {
        assert(isLockedByThisThread();
    }
    void lock() {
        pthread_mutex_lock(&m_mutex);
        holder_= CurrentThread::tid();
    }
    void unlock() {
        holder_ = 0;
        pthread_mutex_unlock(&m_mutex);
    }
    pthread_mutex_t*getPthreadMutex() {
        return &m_mutex;
    }
private:
    pthread_mutex_t m_mutex;
    pid_t holder_;
};

MutexLockGuardCatégorie:


#include"MutexLock.h"
class MutexGuard {
public:
	MutexGuard(MutexLock &mutex):mutex_(mutex) {
		mutex_.lock();
	}
	~MutexGuard(){
		mutex_.unlock();
	}
private:
	MutexLock& mutex_;
};

 

版权声明
本文为[Yan Wei, Digital Media Technology, Jiangnan University]所创,转载请带上原文链接,感谢
https://cdmana.com/2022/01/202201080600041678.html

Scroll to Top