手机版
你好,游客 登录 注册
背景:
阅读新闻

Linux基础编程 多线程中的互斥锁 pthread_mutex_lock

[日期:2012-07-11] 来源:Linux社区  作者:ghostyu [字体:大 中 小]

pthread_mutex.h头文件

  1. #ifndef __SEM_UTIL_H__   
  2. #define __SEM_UTIL_H__   
  3.   
  4. typedef void* SemHandl_t;  
  5.   
  6. SemHandl_t MakeSem(); ///< Initialize the semaphore.   
  7. int SemRelease(SemHandl_t hndlSem); ///< Unlock the semaphore.   
  8. int SemWait(SemHandl_t hndlSem); ///< Lock the semaphore.   
  9. int DestroySem(SemHandl_t hndlSem); ///< Destory the semaphore.   
  10.   
  11.   
  12. #endif  


pthread_mutex.c源文件

  1. /* 
  2. 互斥锁用来保证一段时间内只有一个线程在执行一段代码。 
  3. 必要性显而易见:假设各个线程向同一个文件顺序写入数据, 
  4. 最后得到的结果一定是灾难性的。 
  5. */  
  6. #include <stdio.h>   
  7. #include <stdlib.h>   
  8. #include <unistd.h>   
  9. #include <pthread.h>   
  10.   
  11. #include "pthread_mutex.h"   
  12.   
  13. #define __DEBUG   
  14. #ifdef __DEBUG   
  15. #define DBG(fmt,args...) fprintf(stdout,  fmt,  ##args)   
  16. #else   
  17. #define DBG(fmt,args...)   
  18. #endif   
  19. #define ERR(fmt,args...) fprintf(stderr,  fmt,  ##args)   
  20.   
  21. /*线程互斥锁初始化*/  
  22. SemHandl_t MakeSem()  
  23. {  
  24.     SemHandl_t hndlSem = malloc(sizeof(pthread_mutex_t));  
  25.     if(hndlSem == NULL){  
  26.         ERR("Not enough memory!!\n");  
  27.         return NULL;  
  28.     }  
  29.     /* Initialize the mutex which protects the global data */  
  30.     if(pthread_mutex_init(hndlSem, NULL) != 0){  
  31.         ERR("Sem init faill!!\n");  
  32.         free(hndlSem);  
  33.         return NULL;  
  34.     }  
  35.     return hndlSem;  
  36. }  
  37.   
  38. /*线程互斥锁释放*/  
  39. int SemRelease(SemHandl_t hndlSem)  
  40. {  
  41.     if(hndlSem == NULL){  
  42.         ERR("SemRelease: Invalid Semaphore handler\n");  
  43.         return -1;  
  44.     }  
  45.     return pthread_mutex_unlock(hndlSem);  
  46. }  
  47.   
  48. /*等待*/  
  49. int SemWait(SemHandl_t hndlSem)  
  50. {  
  51.     if(hndlSem == NULL){  
  52.         ERR("SemWait: Invalid Semaphore handler\n");  
  53.         return -1;  
  54.     }  
  55.     return pthread_mutex_lock(hndlSem);  
  56. }  
  57.   
  58. /*删除*/  
  59. int DestroySem(SemHandl_t hndlSem)  
  60. {  
  61.     if(hndlSem == NULL){  
  62.         ERR("DestroySem: Invalid Semaphore handler\n");  
  63.         return -1;  
  64.     }  
  65.     pthread_mutex_lock(hndlSem);  
  66.     pthread_mutex_unlock(hndlSem);  
  67.     if(pthread_mutex_destroy(hndlSem) !=0){  
  68.         ERR("Sem_kill faill!!\n");  
  69.     }  
  70.     free(hndlSem);  
  71.     return 0;  
  72. }  
linux
相关资讯       Linux编程  Linux基础编程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款