tags:

views:

113

answers:

1

I have a chunk of shared memory containing some data. Reading / writing this data needs to be synchronized between different processes. At this moment I'm using unnamed POSIX semaphores. Since my main concern is speed, I'd like to know if semaphores are optimal here? Do they end with a syscall for example (userspace -> kernel space), or force context switches? What would you suggest?

Some info on unnamed semaphores: http://linux.die.net/man/3/sem_init

A: 

Since distinct processes have distinct address spaces, any synchronization feature will have to go through the kernel... except if you manage to synchronize through a chunk of shared memory. And you so happen to have such a chunk.

Therefore, I recommend using a pthreads mutex (see pthread_mutex_lock()) located at some place within your chunk of shared memory. This will work on a recent enough Linux system (glibc-2.3.2 or later, kernel 2.6.x). With a mutex, the kernel will be invoked only upon contention (two processes competing for the same lock), in which case going through the kernel is the right thing to do.

Thomas Pornin
What about atomic variables / spinlocks located in shared memory space? Is pthread_mutex better?
monkey
Atomic variables and spinlocks do half of the job; sometimes this is sufficient. A mutex begins with a spinlock, but if the lock is already owned by another entity, then `pthread_mutex_lock()` will call the kernel to wait for the lock to be released. A raw spinlock will usually end up with busy-waiting, i.e. using CPU while blocking.
Thomas Pornin