进程间通信 - 在共享内存中锁定互斥锁

时间:2013-11-12 13:40:43

标签: c++ posix ipc mutex shared-memory

我有两个执行相同代码的进程:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <pthread.h>


#ifndef _POSIX_THREAD_PROCESS_SHARED
#error This system does not support process shared mutex
#endif

struct shm_content
{
      pthread_mutex_t   mutex;
};

pthread_mutex_t    *mptr; //Mutex Pointer
pthread_mutexattr_t matr; //Mutex Attribute

int   shared_mem_id;      //shared memory Id
int   *mp_shared_mem_ptr; //shared memory ptr -- pointing to mutex

int main (void)
{
    int  rtn;
    size_t shm_size;

    /* initialize shared memory segment */
    shm_size = 1*sizeof(pthread_mutex_t);

    if ((shared_mem_id = shmget(IPC_PRIVATE, shm_size, 0660)) < 0)
    {
        perror("shmget"), exit(1) ;
    }
    if ((mp_shared_mem_ptr = (int *)shmat(shared_mem_id, (void *)0, 0)) == NULL)
    {
        perror("shmat"), exit(1);
    }

    //Offset to find the location of the mutex variable in the shared memory
    shm_content* pcontent = reinterpret_cast<shm_content*>(mp_shared_mem_ptr);

    mptr = &(pcontent->mutex);

    // Setup Mutex
    if (rtn = pthread_mutexattr_init(&matr))
    {
        fprintf(stderr,"pthreas_mutexattr_init: %s",strerror(rtn)),exit(1);
    }
    if (rtn = pthread_mutexattr_setpshared(&matr,PTHREAD_PROCESS_SHARED))
    {
        fprintf(stderr,"pthread_mutexattr_setpshared %s",strerror(rtn)),exit(1);
    }
    if (rtn = pthread_mutex_init(mptr, &matr))
    {
        fprintf(stderr,"pthread_mutex_init %s",strerror(rtn)), exit(1);
    }

        // Lock mutex and then wait for signal to relase mutex
    printf("child mutex lock \n");
    pthread_mutex_lock( mptr );
    printf("child mutex locked\n");

    int i = 0; // :)

    //busy wait
    while (i<10)
    {
        printf("Busy Wait!!! I AM PROCESS 1\n");
        //in the second process will change this line to :
        //printf("Busy Wait!!! I AM PROCESS 2\n");
        sleep(2);
    }

    printf("child mutex unlock\n");
    pthread_mutex_unlock( mptr );
    printf("child mutex unlocked\n");

}

我希望第二个进程只有在第一个进程释放后才能获取互斥锁,但现在它接收了互斥锁的两个副本,并且每个进程都可以自己锁定。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

if ((shared_mem_id = shmget(IPC_PRIVATE, shm_size, 0660)) < 0)
                            ^^^^^^^^^^^

您的共享内存对每个进程都是私有的,因此其中的互斥锁对每个进程都是私有的。

内存和互斥锁将在forks中继承,但这与您当前的设计无关。

您需要非私有共享内存。这是放弃SysV风格的共享内存接口(shmget()等)并采用更简单的POSIX接口(shm_open(), etc.)的好时机。