2

I have two processes rwlock1(parent) and rwlock2(child) . i want to use read-writer lock between processes , i need to transfer pthread_rwlock_t mem_lock to child process, i have a simple code , how can i trasfer the handle . i dont want to use a mutex.

rwlock1(parent)'s code

#include <unistd.h>
#include <pthread.h>
#include <sys/wait.h>

pthread_rwlock_t mem_lock;

int main() {
   pid_t pid;

   //init attr
   pthread_rwlockattr_t mem_lock_attr;
   pthread_rwlockattr_init(&mem_lock_attr);
   pthread_rwlockattr_setpshared(&mem_lock_attr, 1);

   //init read writer lock
   pthread_rwlock_init(&mem_lock, &mem_lock_attr);

   pid = fork();
   if (pid == 0) {
       execl("rwlock2", "rwlock2", (char *) nullptr);
   }

   //wait child
   wait(nullptr);

   return 0;
}




redkont
  • 337
  • 1
  • 2
  • 12

1 Answers1

3

I haven't tried, but it looks like this can be done if you put the lock in shared memory (e.g. set up by mmap or shmget) and use pthread_rwlockattr_setpshared to set the lock as process-shared.

See also 2.9.9 Synchronization Object Copies and Alternative Mappings in IEEE Std 1003.1-2017.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
  • ```pthread_rwlock_t``` defined as ```typedef union { struct __pthread_rwlock_arch_t __data; char __size[__SIZEOF_PTHREAD_RWLOCK_T]; long int __align; } pthread_rwlock_t;``` , so need i do ```memcpy(somewhere in shared memory , (char*)&mem_lock,sizeof( pthread_rwlockattr_t)``` and after pull it from child ? – redkont May 26 '20 at 19:22
  • 1
    It would seem better to just allocate it in shared memory in the first place. Have the parent do `pthread_rwlock_t *rlp = mmap(...); pthread_rwlock_init(rlp,...)`. Then child does `pthread_rwlock_t *rlp2 = mmap(...); pthread_rwlock_rdlock(rlp2,...)` – Nate Eldredge May 26 '20 at 19:26
  • i tried like you said , it works well , thanks , but using like that is safe ? i didnt see behavior of rwlock after exec in man pages . – redkont May 26 '20 at 20:32
  • 1
    I'm not aware of any reason why it wouldn't. I assume the man page doesn't mention exec because there's nothing special about it. Two processes mapping the memory that contains the lock can use it, if it was initialized as process-shared; it shouldn't matter where those processes came from or what image they are executing. – Nate Eldredge May 26 '20 at 20:47