精辟总结:
RAII机制是一种对资源申请、释放这种成对的操作的封装,通过这种方式实现在局部作用域内申请资源然后销毁资源。
常用的就是 智能指针。
详细介绍
在计算机系统中,资源是数量有限且对系统正常运行具有一定作用的元素。比如:网络套接字、互斥锁、文件句柄和内存等等,它们属于系统资源。 由于系统的资源是有限的,我们在编程使用系统资源时,都必须遵循一个步骤:
- 申请资源;
- 使用资源;
- 释放资源。
使用RAII机制封装互斥锁,实现自动申请资源和释放资源。
#include "mutex.h"
class MutexLock {
public:
explicit MutexLock(Mutex *mu)
: mu_(mu) {
this->mu_->Lock();
}
~MutexLock() { this->mu_->Unlock(); }
private:
Mutex *const mu_;
// No copying allowed
MutexLock(const MutexLock&);
void operator=(const MutexLock&);
};
使用:
#include "mutexlock.hpp"
#include <unistd.h>
#include <iostream>
#define NUM_THREADS 10000
int num=0;
Mutex mutex;
void *count(void *args) {
MutexLock lock(&mutex);
num++;
}
int main() {
int t;
pthread_t thread[NUM_THREADS];
for( t = 0; t < NUM_THREADS; t++) {
int ret = pthread_create(&thread[t], NULL, count, NULL);
if(ret) {
return -1;
}
}
for( t = 0; t < NUM_THREADS; t++)
pthread_join(thread[t], NULL);
std::cout << num << std::endl;
return 0;
}
编译并运行:g++ test_mutexlock.cpp mutexlock.hpp mutex.cpp mutex.h -o test_mutexlock -lpthread
./test_mutexlock
运行结果:10000 符合预期(可以去掉MutexLock lock(&mutex);试试看看结果如何?)