首先定义在多进程环境中的锁,采用读写锁,即可以同时读,但只能单独写。
头文件processLock.h
#ifndef PROCESSLOCK_H #define PROCESSLOCK_H #include <pthread.h> #include <dlfcn.h> #include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <stdlib.h> #include <cstring> class ProcessLock { private: pthread_rwlock_t _lock; pthread_rwlockattr_t _attr; ProcessLock(); void init(); static ProcessLock* processLock; public: int read(); int write(); int unlock(); static ProcessLock* createLock(); ~ProcessLock(); }; #endif
源文件processLock.cpp
#include "processLock.h" ProcessLock* ProcessLock::processLock = NULL; void ProcessLock::init() {
//初始化读写锁的属性为进程共享,并与读写锁关联起来。 pthread_rwlockattr_init(&_attr); pthread_rwlockattr_setpshared(&_attr, PTHREAD_PROCESS_SHARED); pthread_rwlock_init(&_lock, &_attr); } int ProcessLock::read() { return pthread_rwlock_rdlock(&_lock); } int ProcessLock::write() { return pthread_rwlock_wrlock(&_lock); }
int ProcessLock::unlock() {
return pthread_rwlock_unlock(&_lock);
} ProcessLock* ProcessLock::createLock() {
//采用mmap实现指针的进程共享,这样在后续获取锁的时候,就是进程间共享的锁。 if (prorcessLock == NULL) { processLock = (ProcessLock)mmap(NULL, sizeof(ProcessLock), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0); processLock->init(); } return processLock; } ProcessLock::~ProcessLock() { pthread_rwlock_destroy(&_lock); pthread_rwlockattr_destroy(&_attr); }
实际应用:
#include "processLock.h" int main() { //child process read, main process write ProcessLock* lock = ProcessLock::createLock(); pid_t fpid = fork(); if (fpid < 0) { cout << "fork error!" << endl; exit(1); } else if (fpid == 0) { cout << "child process" << endl; lock->read(); //do read something lock->unlock(); } else { cout << "parent process" << endl; lock->write(); //do write something lock->unlock(); } return 0; }