【问题标题】:Share pthread mutex between processes在进程之间共享 pthread 互斥锁
【发布时间】:2017-05-04 10:31:14
【问题描述】:

我有这段代码:

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 互斥锁的正确方法吗?

【问题讨论】:

    标签: process pthreads mutex shared-memory


    【解决方案1】:

    如果您想这样做,您必须将互斥体的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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-26
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 2013-12-17
      • 2011-09-22
      相关资源
      最近更新 更多