在进程之间共享pthread互斥锁

时间:2016-12-19 11:20:36

标签: process pthreads mutex shared-memory

我有这段代码:

typedef struct
{
    // ... other fields ...   
    pthread_mutex_t Lock;
} TShared;


const int NPROCESSES=32;   
pid_t pidprocesses[128];
for (int i=0;i<NPROCESSES;i++)
{
   pidprocesses[i]=fork();
   if (!pidprocesses[i])
   {  
      sleep(5); // wait the main process
      int shmid = shmget(1616,sizeof(TShared),0666);
      if (shmid<0)
      {
         printf("Error shmget!\n");
         exit(0);
      }
      TShared *shm = (TShared *) shmat(shmid,NULL,0);
      if (shm==-1)
      {
         printf("Error shmat!\n");
         exit(0);
      }
      bool cond=true;       
      while(cond)
      {
         pthread_mutex_lock(&shm->Lock);
         /* ... other code ... */         
         pthread_mutex_unlock(&shm->Lock);
      }
      exit(0);
   }
}
// main process
int shmid = shmget(1616,sizeof(TShared),IPC_CREAT|0666);
if (shmid<0)
{
   printf("Error shmget!\n");
   exit(0);
}
TShared *shm = (TShared *) shmat(shmid,NULL,0);
if (shm==-1)
{
   printf("Error shmat!\n");
   exit(0);
}
pthread_mutex_init(&shm->Lock,NULL);
/* ... other code ... */
for (int i=0;i<NPROCESSES;i++) waitpid(pidprocesses[i],0,0);

这段代码创建了32个进程,然后使用带有pthread互斥锁的共享内存来同步它们,最后主进程等待子进程的终止。 这是使用pthread互斥锁的正确方法吗?

1 个答案:

答案 0 :(得分:0)

如果您想这样做,必须将互斥锁的pshared属性设置为PTHREAD_PROCESS_SHARED

pthread_mutexattr_t attr;

pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&shm->Lock, &attr);
pthread_mutexattr_destroy(&attr);