当前位置:   article > 正文

QNX共享内存和线程锁实现进程锁

qnx共享内存

直接代码,QNX实测可用;

  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <errno.h>
  7. #include <sys/mman.h>
  8. #include <iostream>
  9. #include <unistd.h>
  10. #include <sys/shm.h>
  11. #include <sys/ipc.h>
  12. #include <errno.h>
  13. static pthread_mutex_t *mptr; /* 互斥锁变量指针,互斥锁变量存放到共享内存 */
  14. #define SHM_NAME "SHM_NAME"
  15. /**
  16. * 多进程互斥锁变量初始化
  17. */
  18. void my_lock_init(char *fg)
  19. {
  20. bool need_init = false;
  21. int fd = shm_open(SHM_NAME, O_RDWR | O_CREAT | O_EXCL, 0777);
  22. if (fd != -1)
  23. {
  24. /* Set the memory object's size */
  25. if (ftruncate(fd, sizeof(pthread_mutex_t)) == -1)
  26. {
  27. fprintf(stderr, "ftruncate: %s\n", strerror(errno));
  28. exit(0);
  29. }
  30. fprintf(stderr, "shm_open: need_init\n");
  31. need_init = true;
  32. }
  33. else if (errno != EEXIST)
  34. {
  35. fprintf(stderr, "shm_open: %d\n", errno);
  36. exit(0);
  37. }
  38. else
  39. {
  40. fprintf(stderr, "shm_open: %d\n", errno);
  41. fd = shm_open(SHM_NAME, O_RDWR, 0777);
  42. if (fd == -1)
  43. {
  44. fprintf(stderr, "shm_open: %s\n", strerror(errno));
  45. exit(0);
  46. }
  47. }
  48. /* Map the memory object */
  49. mptr = (pthread_mutex_t *)mmap(0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  50. if (mptr == MAP_FAILED)
  51. {
  52. fprintf(stderr, "mmap failed: %s\n", strerror(errno));
  53. exit(0);
  54. }
  55. if (need_init)
  56. {
  57. memset(mptr, 0, sizeof(pthread_mutex_t));
  58. pthread_mutexattr_t mattr;
  59. pthread_mutexattr_init(&mattr);
  60. //设置进程间共享
  61. pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
  62. //开启错误检查
  63. pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
  64. pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_ERRORCHECK);
  65. pthread_mutex_init(mptr, &mattr);
  66. pthread_mutexattr_destroy(&mattr);
  67. }
  68. }
  69. /**
  70. * 加锁
  71. */
  72. void
  73. my_lock_wait()
  74. {
  75. int err = pthread_mutex_lock(mptr);
  76. if (err != 0)
  77. {
  78. if (err == EOWNERDEAD)
  79. {
  80. //失败后恢复锁
  81. pthread_mutex_consistent(mptr);
  82. }
  83. }
  84. }
  85. /**
  86. * 解锁
  87. */
  88. void
  89. my_lock_release()
  90. {
  91. pthread_mutex_unlock(mptr);
  92. }
  93. int main(int argc, char **argv)
  94. {
  95. my_lock_init(argv[1]);
  96. int i = 5;
  97. while(i--)
  98. {
  99. std::cout << "test add lock\n";
  100. my_lock_wait();
  101. std::cout << "add lock\n";
  102. sleep(5);
  103. my_lock_release();
  104. std::cout << "release lock\n";
  105. sleep(1);
  106. }
  107. return 0;
  108. }
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号