0% found this document useful (0 votes)
297 views

Mutex and Semaphore

Uploaded by

selvasankar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
297 views

Mutex and Semaphore

Uploaded by

selvasankar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Mutex and Semaphore

Is a key to a toilet. One person can have the key – occupy the toilet – at the time. When finished,

the person gives (frees) the key to the next person in the queue.

Officially: “Mutexes are typically used to serialise access to a section of re-entrant code that

cannot be executed concurrently by more than one thread. A mutex object only allows one thread

into a controlled section, forcing other threads which attempt to gain access to that section to wait

until the first thread has exited from that section.”

Ref: Symbian Developer Library

(A mutex is really a semaphore with value 1.)

Semaphore:

Is the number of free identical toilet keys. Example, say we have four toilets with identical locks

and keys. The semaphore count – the count of keys – is set to 4 at beginning (all four toilets are

free), then the count value is decremented as people are coming in. If all toilets are full, ie. there

are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet,

semaphore is increased to 1 (one free key), and given to the next person in the queue.

Officially: “A semaphore restricts the number of simultaneous users of a shared resource up to a

maximum number. Threads can request access to the resource (decrementing the semaphore),

and can signal that they have finished using the resource (incrementing the semaphore).”

Ref: Symbian Developer Library

Mutex vs. Semaphore

The easiest way to understand the difference is to look at it as a real life situation::

Scenario 1:

There is a room with three (could be more) chairs for people to sit. Any number of people can

attempt to enter the room. How do you ensure

that all the people who enter the room do so only if a seat is available.

Answer:- You assign a gatekeeper who guards the door ??

Scenario 2:

Lets us say there is another room with only one chair, so only one person can be in at any time.

How do you ensure that.

Same answer:-  assign a gatekeeper.

Mutexes and Semaphores are both gatekeepers. We now have to make a choice between which

gatekeeper to use.
The gatekeeper in the first scenario has to be an intelligent one, as he has to do some math. He

has to keep count of how many people are

currently in, how many are going out etc. So if ten people are waiting to get in (because the room

is currently full), the gatekeeper has to

keep all of them waiting. When two of them leave, he notes that and allows two people to get in.

The gatekeeper in the second scenario can afford to be dumb, he just checks if the room is full or

empty and lets one person in if it is

empty. No math, simple.

Semaphore is the intelligent gatekeeper as it keeps track of number of threads that are allowed to

access the resopurce it protects.

Mutex is the dumb guy, he allows only one thread to access his resource.

If you did understand this concept correctly, the first question on your mind should be this.

Can’t the intelligent guy do the dumb guys job. Can’t you replace a Mutex with a Semaphore
What is a semaphore? 

Answer
A semaphore is a variable. There are 2 types of semaphores:

Binary semaphores
Counting semaphores

Binary semaphores have 2 methods associated with it. (up, down / lock, unlock)
Binary semaphores can take only 2 values (0/1). They are used to acquire locks. When a resource is available,
the process in charge set the semaphore to 1 else 0.

Counting Semaphore may have value to be greater than one, typically used to allocate resources from a pool of
identical resources.

What is difference between binary semaphore and mutex?

The differences between binary semaphore and mutex are:

 Mutex is used exclusively for mutual exclusion. Both mutual exclusion and synchronization can be used
by binary.
 A task that took mutex can only give mutex.
 From an ISR a mutex can not be given.s
 Recursive taking of mutual exclusion semaphores is possible. This means that a task that holds before
finally releasing a semaphore, can take the semaphore more than once.
 Options for making the task which takes as DELETE_SAFE are provided by Mutex, which means the
task deletion is not possible when holding the mutex.

What is a semaphore?

A semaphore is hardware or a software tag variable whose value indicates the status of a common resource. Its
purpose is to lock the resource being used. A process which needs the resource will check the semaphore for
determining the status of the resource followed by the decision for proceeding. In multitasking operating systems,
the activities are synchronized by using the semaphore techniques.

Explain the meaning of mutex. 

Answer
A mutex and the binary semaphore are essentially the same. Both can take values: 0 or 1. However, there is a
significant difference between them that makes mutexes more efficient than binary semaphores.

A mutex can be unlocked only by the thread that locked it. Thus a mutex has an owner concept.

What is difference between binary semaphore and mutex?

The differences between binary semaphore and mutex are:

 Mutex is used exclusively for mutual exclusion. Both mutual exclusion and synchronization can be used
by binary.
 A task that took mutex can only give mutex.
 From an ISR a mutex can not be given.
 Recursive taking of mutual exclusion semaphores is possible. This means that a task that holds before
finally releasing a semaphore, can take the semaphore more than once.
 Options for making the task which takes as DELETE_SAFE are provided by Mutex, which means the
task deletion is not possible when holding the mutex.

Explain the meaning of mutex.

Mutex is the short form for ‘Mutual Exclusion object’. A mutex allows multiple threads for sharing the same
resource. The resource can be file. A mutex with a unique name is created at the time of starting a program. A
mutex must be locked from other threads, when any thread that needs the resource. When the data is no longer
used / needed, the mutex is set to unlock.

What is a semaphore? 

Answer
A semaphore is a variable. There are 2 types of semaphores:

Binary semaphores
Counting semaphores

Binary semaphores have 2 methods associated with it. (up, down / lock, unlock)
Binary semaphores can take only 2 values (0/1). They are used to acquire locks. When a resource is available,
the process in charge set the semaphore to 1 else 0.

Counting Semaphore may have value to be greater than one, typically used to allocate resources from a pool of
identical resources.

What is difference between binary semaphore and mutex?

The differences between binary semaphore and mutex are:

 Mutex is used exclusively for mutual exclusion. Both mutual exclusion and synchronization can be used
by binary.
 A task that took mutex can only give mutex.
 From an ISR a mutex can not be given.
 Recursive taking of mutual exclusion semaphores is possible. This means that a task that holds before
finally releasing a semaphore, can take the semaphore more than once.
 Options for making the task which takes as DELETE_SAFE are provided by Mutex, which means the
task deletion is not possible when holding the mutex.

What is a semaphore?

A semaphore is hardware or a software tag variable whose value indicates the status of a common resource. Its
purpose is to lock the resource being used. A process which needs the resource will check the semaphore for
determining the status of the resource followed by the decision for proceeding. In multitasking operating systems,
the activities are synchronized by using the semaphore techniques.
Mutex vs Semaphore

A mutex is analogous to a single key to a room. A person holding the key,


which is analogous to a thread, is the only one who can have access to the
room. The person with the access will then have to give up the key to the next
person in line. Therefore, a mutex can only be released by the thread that
acquires it.

A mutex is normally used to serialize the access to a section of a reentrant


code – a kind of code which is not able to be executed by several threads at
once. Only a single thread is allowed into a section. This forces the other
threads in queue to wait. Before a thread gains access, it will have to wait until
the thread before it gives up the section.

Using the same analogy in mutex, semaphores are the number of similar keys
that can access the same number of rooms with similar locks. A semaphore or
the value of a semaphore count will depend on the number of people (threads)
who enter or exit from the room. If there are 5 rooms and they are all
occupied, then the semaphore count is zero. If two leave the room, then the
count is two and the two keys are given to next two in the queue.

With that being said, semaphores can be concurrently signaled by any thread
or process and are ideal for applications that require synchronization.
Nevertheless, semaphores are used to effectively restrict the number of
concurrent users of a common resource based on the maximum semaphore
count.

So basically, a mutex can be considered as a semaphore having a value of


one.

The decrement and increment of the semaphore are dependent on whether


threads are requesting access to the common resource or leaving the section.

In theory, mutex and (binary) semaphores are semantically similar.The


implementation of the mutex can be done using semaphores and so is the
other way around. However, in the practical sense, they can be a bit different.
Mutexes are intended to be applied for mutual exclusion only and binary
semaphores are intended to be used for mutual exclusion and event
notification. Although they are very similar in terms of implementation and
general semantics, they are used differently.

Summary:

1. Mutex is typically used to serialize access to a common resource while a


semaphore is a number of concurrent accesses.

2. Mutex is like a semaphore with a count of one.


3. Mutex only allows a single thread to have access while semaphores can be
concurrently signaled by any thread or process.

4. Semaphores are ideal for synchronization and often used for event
notification and mutual exclusion while mutex is only applied for mutual
exclusion.

Read more: Difference Between Mutex and Semaphore | Difference Between |


Mutex vs Semaphore http://www.differencebetween.net/language/difference-
between-mutex-and-semaphore/#ixzz1BLMeMGMd
Mutex vs. Semaphore, what is the difference?
The Toilet Example  (c) Copyright 2005, Niclas Winquist ;)

Mutex:

Is a key to a toilet. One person can have the key - occupy the toilet - at the time.
When finished, the person gives (frees) the key to the next person in the queue.

Officially: "Mutexes are typically used to serialise access to a section of  re-entrant


code that cannot be executed concurrently by more than one thread. A mutex
object only allows one thread into a controlled section, forcing other threads
which attempt to gain access to that section to wait until the first thread has
exited from that section."
Ref: Symbian Developer Library

(A mutex is really a semaphore with value 1.)

Semaphore:

Is the number of free identical toilet keys. Example, say we have four toilets with
identical locks and keys. The semaphore count - the count of keys - is set to 4 at
beginning (all four toilets are free), then the count value is decremented as
people are coming in. If all toilets are full, ie. there are no free keys left, the
semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is
increased to 1 (one free key), and given to the next person in the queue.

Officially: "A semaphore restricts the number of simultaneous users of a shared


resource up to a maximum number. Threads can request access to the resource
(decrementing the semaphore), and can signal that they have finished using the
resource (incrementing the semaphore)."
Ref: Symbian Developer Library

5.3. Semaphores and Mutexes


So let us look at how we can add locking to scull. Our goal is to make our operations on
the scull data structure atomic, meaning that the entire operation happens at once as far as
other threads of execution are concerned. For our memory leak example, we need to ensure
that if one thread finds that a particular chunk of memory must be allocated, it has the
opportunity to perform that allocation before any other thread can make that test. To this end,
we must set up critical sections: code that can be executed by only one thread at any given
time.

Not all critical sections are the same, so the kernel provides different primitives for different
needs. In this case, every access to the scull data structure happens in process context as a
result of a direct user request; no accesses will be made from interrupt handlers or other
asynchronous contexts. There are no particular latency (response time) requirements;
application programmers understand that I/O requests are not usually satisfied immediately.
Furthermore, the scull is not holding any other critical system resource while it is accessing
its own data structures. What all this means is that if the scull driver goes to sleep while
waiting for its turn to access the data structure, nobody is going to mind.

"Go to sleep" is a well-defined term in this context. When a Linux process reaches a point
where it cannot make any further processes, it goes to sleep (or "blocks"), yielding the
processor to somebody else until some future time when it can get work done again.
Processes often sleep when waiting for I/O to complete. As we get deeper into the kernel, we
will encounter a number of situations where we cannot sleep. The write method in scull is not
one of those situations, however. So we can use a locking mechanism that might cause the
process to sleep while waiting for access to the critical section.

Just as importantly, we will be performing an operation (memory allocation with kmalloc)


that could sleep—so sleeps are a possibility in any case. If our critical sections are to work
properly, we must use a locking primitive that works when a thread that owns the lock sleeps.
Not all locking mechanisms can be used where sleeping is a possibility (we'll see some that
don't later in this chapter). For our present needs, however, the mechanism that fits best is
a semaphore.

Semaphores are a well-understood concept in computer science. At its core, a semaphore is a


single integer value combined with a pair of functions that are typically called P and V. A
process wishing to enter a critical section will call P on the relevant semaphore; if the
semaphore's value is greater than zero, that value is decremented by one and the process
continues. If, instead, the semaphore's value is 0 (or less), the process must wait until
somebody else releases the semaphore. Unlocking a semaphore is accomplished by calling V;
this function increments the value of the semaphore and, if necessary, wakes up processes
that are waiting.

When semaphores are used for mutual exclusion—keeping multiple processes from running
within a critical section simultaneously—their value will be initially set to 1. Such a
semaphore can be held only by a single process or thread at any given time. A semaphore
used in this mode is sometimes called a mutex, which is, of course, an abbreviation for
"mutual exclusion." Almost all semaphores found in the Linux kernel are used for mutual
exclusion.

You might also like