1进程间pthread_mutex
A依赖的头文件
#include<pthread.h>
B函数声明
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
关于pshared可供选的参数:
线程锁:PTHREAD_PROCESS_PRIVATE
进程锁:PTHREAD_PROCESS_SHARED
默认情况下是线程锁
C案例说明:
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <sys/mman.h> #include <string.h> #include <sys/wait.h>
struct mt { int num; pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; };
int main(void) { int fd,i,err; struct mt *mm; pid_t pid;
fd = open("mt_test",O_CREAT|O_RDWR,0777); /*不需要write,文件里初始值为0*/ ftruncate(fd,sizeof(*mm)); mm = mmap(NULL,sizeof(*mm),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); close(fd);
memset(mm,0,sizeof(*mm));
/*初始化互斥对象属性*/ pthread_mutexattr_init(&mm->mutexattr);
/* * *线程访问,PTHREAD_PROCESS_PRIVATE为同一进程的线程共享 */ pthread_mutexattr_setpshared(&mm->mutexattr,PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&mm->mutex,&mm->mutexattr);
pid = fork(); if(pid == 0) { /*加10次。相当于加10*/ for(i = 0;i < 10;i++) { //在子进程上对文件进行上锁 pthread_mutex_lock(&mm->mutex); (mm->num)++; printf("num++:%d\n",mm->num); //解锁 pthread_mutex_unlock(&mm->mutex); sleep(1); } } else if(pid > 0) { /*父进程完成x+2,加10次,相当于加20*/ for (i = 0;i < 10;i++) { pthread_mutex_lock(&mm->mutex); mm->num += 2; printf("num+=2:%d\n",mm->num); pthread_mutex_unlock(&mm->mutex); sleep(1); } wait(NULL); }
err = pthread_mutex_destroy(&mm->mutex); if(err != 0) { printf("%s\n",strerror(err)); }
/* munmap(mm,sizeof(*mm)); unlink("mt_test"); return 0; } |
运行结果:
总结:
a进程间通信,可以通过内存映射的方式对文件进行操作。
b在上锁的情况下,数字相加后最后得到的是30,加锁后没有出现冲突。
2文件锁
使用fcntl提供文件锁
struct flock {
….
short l_type;
/*Type of lock:F_RDLCK,F_WRLCK,F_UNLCK*/
short l_whence;
/*How to interpretl_start:SEEK_SET,SEET_CUR,SEEK_END*/
off_t l_start;
/*Starting offset for lock*/
off_t l_len;
/*Number of bytes to lock*/
pid_t l_pid;
/*PID of process blocking ourlock(F_GETLK only)*/
….
};
案例说明:
#include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #include<stdlib.h>
void sys_err(char *str) { perror(str); exit(1); }
int main(int argc,char *argv[]) { int fd; struct flock f_lock; if(argc < 2) { printf("./a.out filename\n"); exit(1); }
if((fd = open(argv[1],O_RDWR)) < 0) { sys_err("open"); } //f_lock.l_type = F_WRLCK f_lock.l_type = F_WRLCK; f_lock.l_whence = SEEK_SET; f_lock.l_start = 0; f_lock.l_len = 0;
fcntl(fd,F_SETLKW,&f_lock); printf("get flock\n"); sleep(10); f_lock.l_type = F_UNLCK; fcntl(fd,F_SETLKW,&f_lock); printf("un flock\n");
close(fd); return 0; } |
运行结果:
现象说明:当一个终端在运行的时候,同时打开另外一个终端,同时也执行./app test时发现开始的10秒内不允许操作,现象是test文件被锁住了。也就是说不能同时操作这个文件。