If I have two or more unrelated processes (not threads, and not forked
from a single process) in a multiprocessor environment, can I depend
on a futex to provide synchronization ? (the futex would be in shared
memory mapped by all the processes) I have not used futexes before,
but it seems that the not-contended case is solely in user space.
What should I do to ensure that the writes to shared memory by a
process are visible by another process, possibly running on a
different processor ?
Avik.
Futex interface shall be used on top of something along the lines of the
upcoming std::atomic<> and it's C incarnation ala
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1349.htm
See also
http://www.cl.cam.ac.uk/~pes20/cpp/tech.pdf
regards,
alexander.
Thanks, (this will take me a while to digest!)
Does this mean that for now the simplest way for me to synchronize
shared memory across processes (not threads) is via semaphores?
Avik.
You can use futex interface (lock_queue_wait() and lock_queue_wake())
along the line of
sema_lock:
WHILE // CAS/LL-SC
!atomic_decrement_if_binand_7FFFFFFF_is_not_zero_ccacq(&lock)
lock_queue_wait(&lock, 0) // wait if sem.value is zero
sema_unlock:
uintptr_t lock_queue;
IF atomic_increment_rel(lock_queue = &lock) > 0x80000000
THEN lock_queue_wake(lock_queue, 1)
(try/timed operations omitted for brevity)
BTW, fast mutex:
mutex_lock:
WHILE
atomic_bit_test_set_ccacq(&lock, 1)
lock_queue_wait(&lock, 1) // wait if locked bit is set
mutex_unlock:
uintptr_t lock_queue;
IF atomic_decrement_rel(lock_queue = &lock)
THEN lock_queue_wake(lock_queue, 1)
"ccacq" stands for acquire-but-with-"control condition"-hint
(to avoid redundant memory barrier(s) -- arch specific stuff).
"rel" is a classic release.
regards,
alexander.
You can, but why not use a portable interface that will use futexes
where they're known to work anyway? (Specifically, POSIX process
shared mutexes.)
Yes, I think that is what I will do.
So far I have only used pthread_mutex calls in threads (created using
pthread_create) where the address space is shared. I now gather that I
can use them in dissimilar processes, as long as the pthread_mutex
object is created on shared memory.
Thanks for all the help guys,
Avik.