Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a full memory barrier around sem_post(sem_t * sem) and sem_wait(sem_t * sem)?

Tags:

c++

c

linux

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.

like image 207
hello.co Avatar asked May 08 '13 02:05

hello.co


People also ask

What is Sem_wait and Sem_post?

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).

What is the purpose of the Sem_wait and SEM signal functions?

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.

Does Sem_wait increment?

The sem_wait() and sem_post() functions decrement (wait) or increment (post) the semaphore's value.

What is Sem_post?

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.


2 Answers

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.

like image 188
R.. GitHub STOP HELPING ICE Avatar answered Oct 25 '22 00:10

R.. GitHub STOP HELPING ICE


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.

like image 38
Andrew Tomazos Avatar answered Oct 25 '22 00:10

Andrew Tomazos