互斥量mutex
进程间也可以使用互斥锁,来达到同步的目的。但应在pthread_mutex_init初始化之前,修改其属性为进程间共享。mutex的属性修改函数主要有以下几个。
互斥锁API
pthread_mutexattr_t
mattr 类型 //用于定义mutex锁的【属性】
int pthread_mutexattr_init(pthread_mutexattr_t*attr); //初始化一个mutex属性对象
int pthread_mutexattr_destroy(pthread_mutexattr_t*attr); //销毁mutex属性对象 (而非销毁锁)
intpthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared); //修改mutex属性
参2:pshared取值
- 线程锁:PTHREAD_PROCESS_PRIVATE(mutex的默认属性即为线程锁,进程间私有)
- 进程锁:PTHREAD_PROCESS_SHARED
示例代码
父子进程通过mmap产生的内存映射去进行通信
子进程对num一次+1
父进程对num一次+2
父子进程使用mutex进行互斥的访问mmap中的共享的变量num
#include <fcntl.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/wait.h>
struct mt {
int num;
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
};
int main(void)
{
int fd, i;
struct mt *mm;
pid_t pid;
fd = open("mt_test", O_CREAT | O_RDWR, 0777);
ftruncate(fd, sizeof(*mm));
mm = mmap(NULL, sizeof(*mm), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); //创建内存映射区mm,大小为sizeof(struct mt)
close(fd);
unlink("mt_test");
memset(mm, 0, sizeof(*mm)); //清空内存应摄取
pthread_mutexattr_init(&mm->mutexattr); //初始化mutex属性对象
pthread_mutexattr_setpshared(&mm->mutexattr, PTHREAD_PROCESS_SHARED); //修改属性为进程间共享
pthread_mutex_init(&mm->mutex, &mm->mutexattr); //初始化一把mutex琐
pid = fork();
if (pid == 0) {
for (i = 0; i < 10; i++) {
pthread_mutex_lock(&mm->mutex);
(mm->num)++; //修改内存映射区mm中的num值
printf("-child----num++ %d\n", mm->num);
pthread_mutex_unlock(&mm->mutex);
sleep(1);
}
}
else if (pid > 0) {
for ( i = 0; i < 10; i++) {
sleep(1);
pthread_mutex_lock(&mm->mutex);
mm->num += 2; //修改内存映射区mm中的num值
printf("-parent---num+=2 %d\n", mm->num);
pthread_mutex_unlock(&mm->mutex);
}
wait(NULL);
}
pthread_mutexattr_destroy(&mm->mutexattr); //销毁mutex属性对象
pthread_mutex_destroy(&mm->mutex); //销毁mutex
munmap(mm,sizeof(*mm)); //释放映射区
return 0;
}