c++11 interprocess atomics and mutexes

前端 未结 2 998
孤独总比滥情好
孤独总比滥情好 2020-12-30 02:13

I have a Linux program which spawns several processes (fork) and communicates through POSIX Shared Memory. I\'d like to have each process allocate an id (0-255). My intentio

相关标签:
2条回答
  • 2020-12-30 02:35

    C++11 threading primitives (mutexes, atomics, etc) are threading primitives. They know nothing about processes, and they are not a means of achieving inter-process communication.

    As the C++11 standard makes no mention of processes or inter-process communication, the behavior of such primitives when placed in process-shared memory (a memory-mapped file, some kind of out-of-process globally mapped memory, etc) is undefined.

    0 讨论(0)
  • 2020-12-30 03:00

    You can use mutex inside of shared memory block, but the mutex must be declared as SHARED, therefore is not unusual using mutexes inside of share memory, u can make own class, it is very simple:

    class Mutex {
    private:
        void *_handle;
    public:
        Mutex(void *shmMemMutex,  bool recursive =false, );
        virtual ~Mutex();
    
        void lock();
        void unlock();
        bool tryLock();
    };
    
    Mutex::Mutex(void *shmMemMutex, bool recursive)
    {
        _handle = shmMemMutex;
        pthread_mutexattr_t attr;
        ::pthread_mutexattr_init(&attr);
        ::pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
        ::pthread_mutexattr_settype(&attr, recursive ? PTHREAD_MUTEX_RECURSIVE_NP : PTHREAD_MUTEX_FAST_NP);
    
        if (::pthread_mutex_init((pthread_mutex_t*)_handle, &attr) == -1) {
            ::free(_handle);
            throw ThreadException("Unable to create mutex");
        }
    }
    Mutex::~Mutex()
    {
        ::pthread_mutex_destroy((pthread_mutex_t*)_handle);
    }
    void Mutex::lock()
    {
        if (::pthread_mutex_lock((pthread_mutex_t*)_handle) != 0) {
            throw ThreadException("Unable to lock mutex");
        }
    }
    void Mutex::unlock()
    {
        if (::pthread_mutex_unlock((pthread_mutex_t*)_handle) != 0) {
            throw ThreadException("Unable to unlock mutex");
        }
    }
    bool Mutex::tryLock()
    {
        int tryResult = ::pthread_mutex_trylock((pthread_mutex_t*)_handle);
        if (tryResult != 0) {
            if (EBUSY == tryResult) return false;
            throw ThreadException("Unable to lock mutex");
        }
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题