They asked me this question — what’s the difference between mutex and semaphore during an interview

LORY
6 min readJun 17, 2023

It seems hard for my friend who is a self-taught developer.

Beginning

“Last week they asked me what is multi-threading and if have I ever done anything with that, I answered the question”. my friend said.

“Okay sounds good, hope you will pass it”. I told him.

“But then he asked me how to make sure resources safely be accessed in multi-threading situations”. he said.

“You should know lock right?” I told him.

“Yes I answered him lock but then he asked what is semaphore and what is the difference I have no idea what is semaphore so I told the interviewer I don’t know could you tell me what is that ?”. he said.

“then did he tell you the answer?” I asked.

“Yes, he said semaphore is a signal mechanism which is used for thread synchronization; and the purpose of a mutex is to protect resource access from other threads while only allowing one thread to use it,” he said.

“So you got it?” I asked.

“No…can you explain to me how it works under the hood without too many CS terms?” he asked.

Well, sure let me try.

Mutex

Okay, let’s forget about all these words signal, thread synchronization, and resource access.

Look at my 2 cats they want to eat something for dinner today. so below picture is how mutex works:

So let’s say you are the cat’s owner and you have 2 cats, and there is a special room for cats to eat the food, must go to the room and eat. and these 2 cats don’t share plates, yes they don’t like each other let’s say.

  • #1 cat1 got hungry and found food inside the eating room. (you already dropped the food there)
  • #2 It walked in and start eating then locked the room.
  • #3 owner put cat2 into sleep and watch when cat1 will finish. every 10 seconds to see if cat1 finished eating or no

So far good? let’s continue.

--

--

LORY

A channel which focusing on developer growth and self improvement