赞
踩
直接代码,QNX实测可用;
- #include <pthread.h>
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <errno.h>
- #include <sys/mman.h>
- #include <iostream>
- #include <unistd.h>
- #include <sys/shm.h>
- #include <sys/ipc.h>
- #include <errno.h>
-
- static pthread_mutex_t *mptr; /* 互斥锁变量指针,互斥锁变量存放到共享内存 */
- #define SHM_NAME "SHM_NAME"
-
- /**
- * 多进程互斥锁变量初始化
- */
- void my_lock_init(char *fg)
- {
- bool need_init = false;
- int fd = shm_open(SHM_NAME, O_RDWR | O_CREAT | O_EXCL, 0777);
- if (fd != -1)
- {
- /* Set the memory object's size */
- if (ftruncate(fd, sizeof(pthread_mutex_t)) == -1)
- {
- fprintf(stderr, "ftruncate: %s\n", strerror(errno));
- exit(0);
- }
-
- fprintf(stderr, "shm_open: need_init\n");
- need_init = true;
- }
- else if (errno != EEXIST)
- {
- fprintf(stderr, "shm_open: %d\n", errno);
- exit(0);
- }
- else
- {
- fprintf(stderr, "shm_open: %d\n", errno);
- fd = shm_open(SHM_NAME, O_RDWR, 0777);
- if (fd == -1)
- {
- fprintf(stderr, "shm_open: %s\n", strerror(errno));
- exit(0);
- }
- }
-
- /* Map the memory object */
- mptr = (pthread_mutex_t *)mmap(0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
- if (mptr == MAP_FAILED)
- {
- fprintf(stderr, "mmap failed: %s\n", strerror(errno));
- exit(0);
- }
-
- if (need_init)
- {
- memset(mptr, 0, sizeof(pthread_mutex_t));
- pthread_mutexattr_t mattr;
- pthread_mutexattr_init(&mattr);
- //设置进程间共享
- pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
-
- //开启错误检查
- pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
- pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_ERRORCHECK);
- pthread_mutex_init(mptr, &mattr);
- pthread_mutexattr_destroy(&mattr);
- }
-
- }
-
- /**
- * 加锁
- */
- void
- my_lock_wait()
- {
- int err = pthread_mutex_lock(mptr);
- if (err != 0)
- {
- if (err == EOWNERDEAD)
- {
- //失败后恢复锁
- pthread_mutex_consistent(mptr);
- }
- }
- }
-
- /**
- * 解锁
- */
- void
- my_lock_release()
- {
- pthread_mutex_unlock(mptr);
- }
-
-
- int main(int argc, char **argv)
- {
- my_lock_init(argv[1]);
- int i = 5;
- while(i--)
- {
- std::cout << "test add lock\n";
- my_lock_wait();
- std::cout << "add lock\n";
- sleep(5);
- my_lock_release();
- std::cout << "release lock\n";
- sleep(1);
- }
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。