In linux code, I remember hearing there is a full memory barrier around mutex_lock(). I want to make sure whether it is around sem_xxx also.
To lock a semaphore or wait we can use the sem_wait function: int sem_wait(sem_t *sem); To release or signal a semaphore, we use the sem_post function: int sem_post(sem_t *sem); A semaphore is initialised by using sem_init(for processes or threads) or sem_open (for IPC).
The sem_wait() function decrements by one the value of the semaphore. The semaphore will be decremented when its value is greater than zero. If the value of the semaphore is zero, then the current thread will block until the semaphore's value becomes greater than zero.
The sem_wait() and sem_post() functions decrement (wait) or increment (post) the semaphore's value.
The sem_post() function unlocks the semaphore referenced by sem by performing a semaphore unlock operation on that semaphore. If the semaphore value resulting from this operation is positive, then no threads were blocked waiting for the semaphore to become unlocked; the semaphore value is simply incremented.
The authoritative answer is here:
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11
Applications shall ensure that access to any memory location by more than one thread of control (threads or processes) is restricted such that no thread of control can read or modify a memory location while another thread of control may be modifying it. Such access is restricted using functions that synchronize thread execution and also synchronize memory with respect to other threads. The following functions synchronize memory with respect to other threads: ...
sem_wait
and sem_post
are in the list, so they are full memory barriers.
Yes, it uses an atomic increment/decrement in the uncontended case, which of course has a membar. For the contended case there is a system call to futex, which also has a membar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With