Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between lock, memory barrier, semaphore

This article: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf (page 12) seems to make a difference between a lock and a memory barrier

I would like to know what the difference is between a lock, memory barrier, and a semaphore?

(While other questions might mention the difference between a lock and a synchronisation object, I found none about the difference between a lock and a memory barrier)

like image 898
xcrypt Avatar asked May 11 '12 13:05

xcrypt


People also ask

What is the difference between a lock and a semaphore?

Semaphores are used to provide mutual exclusion and condition synchronization. Locks provide mutual exclusion and have special properties that make them useful in object-oriented programs.

What is difference between mutex and semaphore?

A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore.

What is difference between mutex and lock?

A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes. A mutex is the same as a lock but it can be system wide (shared by multiple processes).

Is mutex a memory barrier?

So locking a mutex and immediately unlocking it acts as a memory barrier, albeit a horribly inefficient one since it forces serial execution. Show activity on this post. Mutex and other lock in kernel uses the barrier internally to ensure that code runs in the exact order as expected.

Which is faster semaphore or mutex?

ii) Mutex is lightweight and faster than semaphore. Futex is even faster. iii) Mutex can be acquired by same thread successfully multiple times with condition that it should release it same number of times.


1 Answers

  • A memory barrier is a method to order memory access. Compilers and CPU's can change this order to optimize, but in multithreaded environments, this can be an issue. The main difference with the others is that threads are not stopped by this.
  • A lock or mutex makes sure that code can only be accessed by 1 thread. Within this section, you can view the environment as singlethreaded, so memory barriers should not be needed.
  • a semaphore is basically a counter that can be increased (v()) or decreased (p()). If the counter is 0, then p() halts the thread until the counter is no longer 0. This is a way to synchronize threads, but I would prefer using mutexes or condition variables (controversial, but that's my opinion). When the initial counter is 1, then the semaphore is called a binary semaphore and it is similar to a lock.

A big difference between locks and semaphores is that the thread owns the lock, so no other thread should try to unlock, while this is not the case for semaphores.

like image 110
stefaanv Avatar answered Sep 27 '22 22:09

stefaanv