进程间同步可以使用互斥量mutex(互斥锁)、信号量和文件锁。
进程间同步使用信号量:
int sem_init(sem_t *sem, int pshared, unsigned int value);
用于进程间同步此时第二个参数不能取0了,取非0值用于进程间同步,一般取1,也可按照下述方法取值,即:PTHREAD_PROCESS_SHARED。
(1)进程间使用互斥量进行同步
在pthread_mutex_init初始化之前,修改其属性为进程间共享。mutex的属性修改函数主要有以下几个:
pthread_mutexattr_t mattr 类型:用于定义mutex锁的属性;
int pthread_mutexattr_init(pthread_mutexattr_t *attr); 初始化一个mutex属性对象;
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared); 修改mutex属性;参2:pshared取值:进程锁:PTHREAD_PROCESS_SHARED; 线程锁:PTHREAD_PROCESS_PRIVATE (mutex的默认属性即为线程锁,进程间私有)
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr); 销毁mutex属性对象 (而非销毁锁)
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); 即将修改后的属性传入该函数,即可产生一个进程锁。
//进程间使用互斥量来实现同步
#include
#include
#include
#include
#include
#include
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)++;
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;
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;
}
[root@localhost 02_pthread_sync_test]# ./process_mutex
-child----------num++ 1
-------parent---num+=2 3
-child----------num++ 4
-------parent---num+=2 6
-child----------num++ 7
-child----------num++ 8
-------parent---num+=2 10
-------parent---num+=2 12
-child----------num++ 13
-------parent---num+=2 15
-child----------num++ 16
-child----------num++ 17
-------parent---num+=2 19
-child----------num++ 20
-------parent---num+=2 22
-child----------num++ 23
-------parent---num+=2 25
-child----------num++ 26
-------parent---num+=2 28
-------parent---num+=2 30