gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:01:01 89 4
gpt4 key购买 nike

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

#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");

}

我预计第二个进程只能在第一个进程释放互斥量后才能获取互斥量,但现在它接缝有 2 个互斥量拷贝,每个进程都可以锁定自己的。

有什么想法吗?

最佳答案

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

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

内存和互斥量将在 fork 之间继承,但这与您当前的设计无关。

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

关于c++ - 进程间通信——在共享内存中锁定互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19930741/

89 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com