接上一篇:linux_信号量函数系列-信号量实现生产者消费者模型-sem_init函数-sem_wait函数-sem_post函数-sem_trywait函数
今天来分析进程锁和线程锁,进程锁需要用到pthread_mutexattr_init函数、pthread_mutexattr_destroy函数、pthread_mutexattr_setpshared函数,而文件锁则需要用到fcntl函数,话不多说,开始上菜:
此博主在CSDN发布的文章目录:我的CSDN目录,作为博主在CSDN上发布的文章类型导读
目录
1.互斥量mutex–进程锁
进程间也可以使用互斥锁,来达到同步的目的。但应在pthread_mutex_init初始化之前,修改其属性为进程间共享。mutex的属性修改函数主要有以下几个。
pthread_mutexattr_t mattr 类型: 用于定义mutex锁的【属性】
1.1.pthread_mutexattr_init函数
函数作用:
初始化一个mutex属性对象。
头文件:
#include <pthread.h>
函数原型:
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
函数参数:
attr:需要初始化的mutex属性对象
返回值:
成功:返回0;
失败:返回非0。
注意:
1.2.pthread_mutexattr_destroy函数
函数作用:
销毁mutex属性对象 (而非销毁锁)。
头文件:
#include <pthread.h>
函数原型:
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
函数参数:
attr:需要销毁的mutex属性对象
返回值:
成功:返回0;
失败:返回非0
注意:
1.3.pthread_mutexattr_setpshared函数
函数作用:
修改mutex属性。
头文件:
#include <pthread.h>
函数原型:
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);
函数参数:
attr:mutex属性对象
pshared:可设置为进程锁还是线程锁
线程锁取值:PTHREAD_PROCESS_PRIVATE (mutex的默认属性即为线程锁,进程间私有)
进程锁取值:PTHREAD_PROCESS_SHARED
返回值:
成功:返回0;
失败:返回非0
1.4.进程间mutex示例
进程间使用mutex来实现同步,代码如下:
#include <fcntl.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 fd, i;
struct mt *mm;
pid_t pid;
fd = open("mt_test", O_CREAT | O_RDWR, 0777);
ftruncate(fd, sizeof(*mm)

文章介绍了Linux下如何使用互斥量实现进程锁,包括pthread_mutexattr_init、pthread_mutexattr_destroy、pthread_mutexattr_setpshared等函数的用法,以及如何通过fcntl函数实现文件锁,提供了一个进程间使用mutex同步的示例和文件锁的使用示例。

92

被折叠的 条评论
为什么被折叠?



