linux_进程锁与文件锁-pthread_mutexattr_init函数-pthread_mutexattr_setpshared函数

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

接上一篇: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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

futureCode.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值