Chinaunix首页 | 论坛 | 博客
  • 博客访问: 338922
  • 博文数量: 97
  • 博客积分: 2130
  • 博客等级: 大尉
  • 技术积分: 1800
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-24 11:51
文章分类
文章存档

2013年(57)

2012年(40)

我的朋友

分类: C/C++

2013-01-31 09:49:36

 

C++程序的设计机制3 RAII机制(3)

为了管理内存等资源,C++程序员通常采用RAII机制(资源获取即初始化),在使用资源的类的构造函数中申请资源,然后使用,最后在析构函数中释放资源。今天本文为你介绍RAII机制,一起来看。

AD:

3)锁操作

1.  /*  

2.  * =====================================================================================  

3.  *  

4.  * Filename: threadlock.cpp  

5.  *  

6.  * Description: Lock for RAII  

7.  *  

8.  * Version: 1.0  

9.  * Created: 05/09/2011 10:16:13 PM  

10.* Revision: none  

11.* Compiler: g++  

12.*  

13.* Author: gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com  

14.*  

15.* =====================================================================================  

16.*/ 

17.#include   

18.#include   

19.#include   

20.int counter = 0;  

21.void* routine(void *ptr);  

22.pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  

23.class NonCopyable  

24.{  

25.public:  

26.NonCopyable(){};  

27.private:  

28.NonCopyable (NonCopyable const &); // private copy constructor  

29.NonCopyable & operator = (NonCopyable const &); // private assignment operator  

30.};  

31.class ScopeMutex:NonCopyable  

32.{  

33.public:  

34.ScopeMutex(pthread_mutex_t* mutex):mutex_(mutex){  

35.pthread_mutex_lock( mutex_ );  

36.}  

37.~ScopeMutex(){  

38.pthread_mutex_unlock( mutex_ );  

39.}  

40.private:  

41.pthread_mutex_t *mutex_;  

42.};  

43.int main(int argc, char *argv[])  

44.{  

45.int rc1, rc2;  

46.pthread_t thread1, thread2;  

47.if( (rc1=pthread_create( &thread1, NULL, routine, NULL)) )  

48.{  

49.printf("Thread creation failed: %d\n", rc1);  

50.}  

51.if( (rc2=pthread_create( &thread2, NULL, routine, NULL)) )  

52.{  

53.printf("Thread creation failed: %d\n", rc1);  

54.}  

55.pthread_join( thread1, NULL);  

56.pthread_join( thread2, NULL);  

57.}  

58.void* routine(void *ptr)  

59.{  

60.ScopeMutex scopeMutex(&mutex);  

61.counter++;  

62.printf("%d\n",counter);  

63.} 

2.总结

RAII机制保证了异常安全,并且也为程序员在编写动态分配内存的程序时提供了安全保证。缺点是有些操作可能会抛出异常,如果放在析构函数中进行则不能将错误传递出去,那么此时析构函数就必须自己处理异常。这在某些时候是很繁琐的。参考资料

 

 

阅读(1493) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~