• c++ fork进程与同步锁


    首先定义在多进程环境中的锁,采用读写锁,即可以同时读,但只能单独写。

    头文件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;
    }
  • 相关阅读:
    js获取当前时间,日期格式为年月日
    create-react-app里添加less
    react css 模块化
    react 点击父级元素 不触发子级元素click事件
    react-router-dom 实现路由左右滑动进入页面的效果
    vue路由左右侧滑动 react路由左右侧滑动
    react 父组件不能直接在子组件上加className,也得用props传递过去
    react 父组件调用子组件方法
    css滚动相关问题记录
    javascript异步编程的几种方法
  • 原文地址:https://www.cnblogs.com/sssblog/p/10457114.html
Copyright © 2020-2023  润新知