user6171116
user6171116

Reputation:

Share pthread mutex between processes

I have this piece of code:

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

This piece of code create 32 processes and then use shared memory with a pthread mutex to synchronize them and in the end the main process wait for the terminations of the childs. Is this the correct way use a pthread mutex?

Upvotes: 0

Views: 1876

Answers (1)

caf
caf

Reputation: 239041

You must set the pshared attribute of the mutex to PTHREAD_PROCESS_SHARED if you want to do that:

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

Upvotes: 1

Related Questions