Linux下使用pthread实现进程锁的注意事项

1. 背景

最近通过共享内存mmap实现多进程的数据共享,使用PTHREAD_PROCESS_SHARED时写错了,导致进程锁不起作用。

2. 接口

接口说明如下,用法与多线程的互斥锁类似,但需要额外设置一下PTHREAD_PROCESS_SHARED

SYNOPSIS
       #include <pthread.h>

       int pthread_mutexattr_getpshared(
                             const pthread_mutexattr_t *restrict attr,
                             int *restrict pshared);
       int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr,
                             int pshared);

       Compile and link with -pthread.

DESCRIPTION
       These  functions  get  and  set  the process-shared attribute in a mutex attributes object.  This attribute must be appropriately set to ensure correct, efficient operation of a
       mutex created using this attributes object.

       The process-shared attribute can have one of the following values:

       PTHREAD_PROCESS_PRIVATE
              Mutexes created with this attributes object are to be shared only among threads in the same process that initialized the  mutex.   This  is  the  default  value  for  the
              process-shared mutex attribute.

       PTHREAD_PROCESS_SHARED
              Mutexes  created  with  this attributes object can be shared between any threads that have access to the memory containing the object, including threads in different pro‐
              cesses.

3 代码

实现一个N个进程同时操作一块共享内存的代码,8个进程每个对变量进行val++操作10w次,所以是期望最终结果是80w次就为正确。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <pthread.h>

#include <sys/stat.h>
#include 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值