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