Lock, mutex and semaphore difference

Weidian Huang
1 min readJul 19, 2020

--

Lock

A lock only allows one thread to enter the part of code inside the locked scope.

For example, in the gym, there is one locker shared by multiple users. If someone has already used it, it will be locked, anyone else can not use it until the previous person unlocks it.

Lock is not shared with any other processes, it can be only used by current process.

Mutex

A mutex (Mutual exclusion) is the same as a lock but it can be system wide (shared by multiple processes). It is used to synchronise access to a resource.

Semaphore

A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Multiple threads can get the access to the resource (decrementing the semaphore), and can signal that they have finished the usage of the resource (incrementing the semaphore).

For example, everyday the company gym only gives maximum 3 free access cards. The first 3 persons will get the access card. The next person comes, he/she need to wait until any of previous 3 persons returned the card.

--

--

Weidian Huang
Weidian Huang

Written by Weidian Huang

Android developer likes to dig deeper into the issues

No responses yet