C++封装互斥锁和基于RAII机制能自动解锁的互斥锁
Posted 奇妙之二进制
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++封装互斥锁和基于RAII机制能自动解锁的互斥锁相关的知识,希望对你有一定的参考价值。
#include "base/mutex.h"
Mutex::Mutex() { pthread_mutex_init(&mutex_, NULL); }
Mutex::~Mutex() { pthread_mutex_destroy(&mutex_); }
void Mutex::Lock() { pthread_mutex_lock(&mutex_); }
void Mutex::Unlock() { pthread_mutex_unlock(&mutex_); }
MutexLockGuard::MutexLockGuard(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); }
MutexLockGuard::~MutexLockGuard() { mutex_->Unlock(); }
#ifndef _MUTEX_H_
#define _MUTEX_H_
#include <pthread.h>
class Mutex {
public:
Mutex();
~Mutex();
void Lock();
void Unlock();
pthread_mutex_t* Get() { return &mutex_; };
private:
pthread_mutex_t mutex_;
};
class MutexLockGuard {
public:
MutexLockGuard(Mutex* mutex);
~MutexLockGuard();
private:
Mutex* mutex_;
};
#endif //_MUTEX_H_
以上是关于C++封装互斥锁和基于RAII机制能自动解锁的互斥锁的主要内容,如果未能解决你的问题,请参考以下文章