pthread mutex 进程间互斥锁
Posted tianrks
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pthread mutex 进程间互斥锁相关的知识,希望对你有一定的参考价值。
共享标志 | 定义 | 名称 | 描述 |
0 | PTHREAD_PROCESS_PRIVATE | 进程内互斥锁 | 仅可当前进程内共享 |
1 | PTHREAD_PROCESS_SHARED | 进程间互斥锁 | 多个进程间共享 |
第一个程序代码
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> int main(int argc, char* argv[]) { char mmap_file_path[512] = { 0 }; getcwd(mmap_file_path, sizeof(mmap_file_path)); strcat(mmap_file_path, "/pthread_shared"); int fd = open(mmap_file_path, O_RDWR | O_CREAT, 0744); if (0 < fd) { //重置文件大小 ftruncate(fd, sizeof(pthread_mutex_t)); pthread_mutex_t* mutex_ptr = (pthread_mutex_t*)mmap(0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); //初始化锁对象 pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(mutex_ptr, &attr);int lock_ret = pthread_mutex_lock(mutex_ptr); if (0 == lock_ret) { printf("lock successed\n"); usleep(10 * 1000 * 1000); pthread_mutex_unlock(mutex_ptr); } else { printf("lock failed: %d\n", lock_ret); } } else { printf("open err\n"); } return 0; }
第二个程序代码,特殊的在获取锁对象后不需要初始化,因为在第一个进程内已经初始化了
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> int main(int argc, char* argv[]) { char mmap_file_path[512] = { 0 }; getcwd(mmap_file_path, sizeof(mmap_file_path)); strcat(mmap_file_path, "/pthread_shared"); int fd = open(mmap_file_path, O_RDWR | O_CREAT, 0744); if (0 < fd) { pthread_mutex_t* mutex_ptr = (pthread_mutex_t*)mmap(0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd);int lock_ret = pthread_mutex_lock(mutex_ptr); if (0 == lock_ret) { printf("lock successed\n"); usleep(10 * 1000 * 1000); pthread_mutex_unlock(mutex_ptr); } else { printf("lock failed: %d\n", lock_ret); } } else { printf("open err\n"); } return 0; }
以上是关于pthread mutex 进程间互斥锁的主要内容,如果未能解决你的问题,请参考以下文章
临界区(critical section 每个线程中访问 临界资源 的那段代码)和互斥锁(mutex)的区别(进程间互斥量共享内存虚拟地址)