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


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. }  
  • 1
  • 2
  • 下一页

相关内容