进程间同步
来源:互联网 发布:淘宝分类怎么没了 编辑:程序博客网 时间:2024/06/02 03:57
互斥量mutex
进程间也可以使用互斥锁,来达到同步的目的。但应在pthread_mutex_init初始化之前,修改其属性为进程间共享。
mutex的属性修改函数主要有以下几个。
主要应用函数:
pthread_mutexattr_t mattr 类型: 用于定义mutex锁的【属性】
pthread_mutexattr_init函数: 初始化一个mutex属性对象
int pthread_mutexattr_init(pthread_mutexattr_t*attr);
pthread_mutexattr_destroy函数: 销毁mutex属性对象 (而非销毁锁)
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
pthread_mutexattr_setpshared函数: 修改mutex属性。
intpthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);
参2:pshared取值:
线程锁:PTHREAD_PROCESS_PRIVATE(mutex的默认属性即为线程锁,进程间私有)
进程锁:PTHREAD_PROCESS_SHARED
进程间mutex示例
#include <stdio.h>#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.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 i;
struct mt *mm;
pid_t pid;
/*
int 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);
close(fd);
unlink("mt_test");
*/
mm = mmap(NULL, sizeof(*mm), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0);
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)++;
pthread_mutex_unlock(&mm->mutex);
printf("-child----------num++ %d\n", mm->num);
}
} else if (pid > 0) {
for ( i = 0; i < 10; i++) {
// sleep(1);
pthread_mutex_lock(&mm->mutex);
mm->num += 2;
pthread_mutex_unlock(&mm->mutex);
printf("-------parent---num+=2 %d\n", mm->num);
}
wait(NULL);
}
pthread_mutexattr_destroy(&mm->mutexattr); //销毁mutex属性对象
pthread_mutex_destroy(&mm->mutex); //销毁mutex
munmap(mm,sizeof(*mm)); //释放映射区
return 0;
}
- 进程/线程间同步
- 进程/线程间同步
- 进程间协作、同步
- 进程间同步 信号量
- 进程线程间同步
- 进程间同步问题
- linux进程间同步
- python进程间同步
- python进程间同步
- 进程间通信,同步
- 进程间同步
- 进程间同步
- 进程间通信和同步
- VB 进程间同步通讯
- 进程间同步的方法
- 进程间同步之--信号量
- windows中的进程间同步
- 进程/线程间同步机制。
- 51nod 1640 天气晴朗的魔法
- hhh
- Java进阶05 多线程
- 笔记:iOS动画
- 短信验证
- 进程间同步
- osgi入门(二)
- JDBC入门(一)基本CRUD操作
- 输入一个整数a,再输入两个整数p1,p2(p1,p2<32),输出该整数的二进制表示方法中从右端开始的p1到p2位.
- java 工具箱 AOP
- 彻底理解Python切片
- 1022: [SHOI2008]小约翰的游戏John
- JavaScript中数组的使用
- 怎么使用C++标准库来实现二维数组