我们知道 Mutex 互斥量是可以用在线程间同步的,线程之间共享进程的数据,mutex 就可以直接引用。而进程有自己独立的内存空间,要怎样将它应用在进程间同步呢?为了达到这一目的,可以在 pthread_mutex_init 初始化之前,修改其属性为进程间共享,并将其映射到共享内存中即可。
--------------------------------------------------------------------------------
使用到的API:
pthread_mutexattr_t mattr 类型: 用于定义互斥量的属性
pthread_mutexattr_init 函数: 初始化一个mutex属性对象
pthread_mutexattr_destroy 函数: 销毁 mutex 属性对象
pthread_mutexattr_setpshared 函数: 修改 mutex 属性。
pthread_mutexattr_setpshared 函数使用:
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);
pshared 参数:它有以下两个取值:
线程锁:PTHREAD_PROCESS_PRIVATE (mutex的默认属性即为线程锁,进程间私有)
进程锁:PTHREAD_PROCESS_SHARED
要想实现进程间同步,需要将 mutex 的属性改为 PTHREAD_PROCESS_SHARED。
应用实例:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/wait.h>
/* 定义 mutex */
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
int main()
{
int i = 0;
pid_t pid;
pthread_mutex_t *m_mutex;
/* mutex attr 初始化 */
pthread_mutexattr_init(&mutexattr);
/* 修改属性 */
pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED);
/* mutex 初始化 */
pthread_mutex_init(&mutex, &mutexattr);
/* 将 mutex 共享 */
m_mutex = (pthread_mutex_t*) mmap(NULL, sizeof(mutex), PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_ANON, -1, 0);
pid = fork();
if(pid == 0){
for(; i<3; i++){
sleep(1);
pthread_mutex_lock(m_mutex);
puts("This is the child process!");
pthread_mutex_unlock(m_mutex);
}
}else if(pid > 0){
for(; i<3; i++){
sleep(1);
pthread_mutex_lock(m_mutex);
puts("This is the parent process!");
pthread_mutex_unlock(m_mutex);
}
/* 回收子进程资源 */
wait(NULL);
}
/* 销毁 mutex */
pthread_mutexattr_destroy(&mutexattr);
pthread_mutex_destroy(&mutex);
/* 取消映射 */
munmap(m_mutex, sizeof(mutex));
return 0;
}
运行结果:
[root@localhost 24th_processSync]# ./a.out
This is the parent process!
This is the child process!
This is the parent process!
This is the child process!
This is the parent process!
This is the child process!
Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx