JB_User
JB_User

Reputation: 3267

Non-exclusive shared memory lock in C

I'm on Linux and I want to share memory between about 5-10 processes (each is a C program). I know how to do this with either the POSIX semaphores (sem_open, sem_wait, sem_post, etc) or the other semaphores (semctl, semget, semop, etc). The problem is I only know how to do exclusive semaphore locks. I want non-exclusive locks.

In my application, only one process writes to shared memory, while all others only read it. I'd like to be able to do non-exclusive read locks on the semaphore (like with the shell command flock). Can I do this with POSIX semaphores or semctl()? Or is there another way to do this?

Upvotes: 2

Views: 619

Answers (1)

Jens Gustedt
Jens Gustedt

Reputation: 78993

The tool for you are read-write locks pthread_rwlock_t. Linux implements them well in shared memory between different processes. Have a look into pthread_rwlock_init, pthread_rwlockattr_init and pthread_rwlockattr_setpshared to see how to enable them in shared memory.

Upvotes: 4

Related Questions