我们知道 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/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <string.h>
/* 定义 mutex */
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
int main()
{
int shm_id = 0;
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);
/* 申请共享内存 */
shm_id = shmget((key_t)1004, sizeof(mutex), IPC_CREAT | 0600);
/* 映射共享内存到进程地址空间 */
m_mutex = (pthread_mutex_t*)shmat(shm_id, 0, 0);
memcpy(m_mutex, &mutex, sizeof(mutex));
pid = fork();
if(pid == 0){
pthread_mutex_lock(m_mutex);
for(; i<3; i++){
pthread_mutex_lock(m_mutex);
puts("This is the child process!");
}
}else if(pid > 0){
for(; i<3; i++){
sleep(1);
pthread_mutex_unlock(m_mutex);
puts("This is the parent process!");
}
/* 回收子进程资源 */
wait(NULL);
}
/* 销毁 mutex */
pthread_mutexattr_destroy(&mutexattr);
pthread_mutex_destroy(&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!