我有两个进程将执行相同的代码:
#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");
}我希望第二个进程只能在第一个进程释放互斥锁后才能获取它,但现在它认为互斥锁有两个副本,每个进程都可以锁定自己的互斥锁。
有什么想法吗?
发布于 2013-11-12 22:25:50
if ((shared_mem_id = shmget(IPC_PRIVATE, shm_size, 0660)) < 0)
^^^^^^^^^^^您的共享内存是每个进程专用的,因此其中的互斥锁是每个进程专用的。
内存和互斥量将跨fork继承,但这与您当前的设计无关。
您需要非私有共享内存。现在是放弃SysV风格的共享内存接口(shmget()等)的好时机。并采用更简单的POSIX接口(shm_open(), etc.)。
https://stackoverflow.com/questions/19930741
复制相似问题