The document discusses three classic synchronization problems: the bounded buffer problem, dining philosophers problem, and readers-writers problem. For the bounded buffer problem, it describes the producer-consumer scenario and provides pseudocode for the producer and consumer using semaphores. For the dining philosophers problem, it outlines the scenario of philosophers sharing a limited number of chopsticks and presents a solution using semaphores. For the readers-writers problem, it describes the scenario of multiple readers and a single writer accessing a shared resource and provides pseudocode for readers and writers that uses semaphores and a lock to control access.
The Dining Philosopher Problem – The Dining Philosopher Problem states that K philosophers seated around a circular table with one chopstick between each pair of philosophers. There is one chopstick between each philosopher. A philosopher may eat if he can pick up the two chopsticks adjacent to him.
Semaphore = a synchronization primitive
higher level of abstraction than locks
invented by Dijkstra in 1968, as part of the THE operating system
A semaphore is:
a variable that is manipulated through two operations, P and V (Dutch for “test” and “increment”)
P(sem) (wait/down)
block until sem > 0, then subtract 1 from sem and proceed
V(sem) (signal/up)
add 1 to sem
Do these operations atomically
Repetition Control and IO ErrorsPlease note that the mate.docxsodhi3
Repetition Control and I/O Errors
Please note that the material on this website is not intended to be exhaustive.
This is intended as a summary and supplementary material to required textbook.
INTRODUCTION
Repetition control (also called loop control or just looping) is widely used in programming to reduce the
amount of simple sequential statements. File I/O errors are encountered when inputs (both file input and
user input) are not what the program expected.
THE while LOOP
With all looping mechanisms we will have a block of code (enclosed in curly braces) within the loop.
This block of code is called the body of the loop. The intention of the loop is to execute the same block
of code repetitively. Looping obviates the need to write overlong programs with the same statements
executed sequentially.
Some caution must be exercised when using the while loop, and these cautions all relate to the use of the
loop control variable or condition. The while loop has the following form:
while (loop_control_condition_is_true) {
// the statements in the body of the loop go
// here
}
Note that there is no semicolon (;) at the end of the loop block and that the body of the loop is contained
within curly braces. Note further the loop control condition is always evaluated at the top of the loop.
The number of times that the loop body is executed is determined by the use of the loop control
condition, which is a logical expression that must evaluate to true or to false. The loop body may be
executed 0 or more times. For instance, the body of the loop is not executed at all if the loop control
condition evaluates to false when the loop is encountered in your program. Usually, however, we want
the loop to execute at least once. If so, that brings us to the first important caution:
If you want the loop body to execute at least once, you must ensure that the loop control condition
evaluates to true when the while loop is encountered in your program. For example:
bool cond = true;
...
while (cond) {
...
}
Once we are sure that the loop body will execute at least once, we have to pay attention to the second
caution:
If you want to avoid an infinite loop (where the loop is never exited) you must ensure that the loop
control condition is made to evaluate false at some point within the body of the loop. For example:
const int MAX = 1000;
int i = 0;
...
while (i < MAX) {
...
i++;
}
The loop control condition can be a simple logical expression, or it can be a fairly complicated one. For
instance:
while (((i < MAX) && cond) || keep_going) ...
Using the KISS principle (Keep It Simple, Smarty) it is always advisable to keep the loop control
condition as simple as possible.
Some programmers are purists about loop control conditions, and believe the while loop should never be
exited except at the top of the loop (when the loop control condition becomes false). C++, however, has
two statemen ...
A brief introduction to Process synchronization in Operating Systems with classical examples and solutions using semaphores. A good starting tutorial for beginners.
Introduction to interprocess communication issues like race conditions and critical regions. Solutions such as mutual exclusion with busy waiting, sleep and wakeup, Semaphores, mutexes, monitors, barriers, and message passing.
Describe synchronization techniques used by programmers who develop .pdfexcellentmobiles
Describe synchronization techniques used by programmers who develop applications for
LUBUNTU (LINUX)
Solution
Concurrency and locking: Synchronization methods are necessary when the property of
concurrency exists. Concurrency exists when two or more processes execute over the same time
period and potentially interact with one another. The Linux kernel supports concurrency in both
modes. The kernel itself is dynamic, and race conditions can be created in a number of ways. The
Linux kernel also supports multiprocessing known as symmetric multiprocessing (SMP).
Concurrency can occur on uniprocessor (UP) hosts where multiple threads share the same CPU
and preemption creates race conditions. Preemption is sharing the CPU transparently by
temporarily pausing one thread to allow another to execute. A race condition occurs when two or
more threads manipulate a shared data item and the result depends upon timing of the execution.
Concurrency also exists in multiprocessor (MP) machines, where threads executing
simultaneously in each processor share the same data. Note that in the MP case there is true
parallelism because the threads execute simultaneously. In the UP case, parallelism is created by
preemption. The difficulties of concurrency exist in both modes.
To combat the issue of race conditions, the concept of a critical section was created. A critical
section is a portion of code that is protected against multiple access. This portion of code can
manipulate shared data or a shared service (such as a hardware peripheral). Critical sections
operate on the principle of mutual exclusion.
Race condition Situation where simultaneous manipulation of a resource by two or more threads
causes inconsistent results.
Critical section Segment of code that coordinates access to a shared resource.
Mutual exclusion Property of software that ensures exclusive access to a shared resource.
Deadlock Special condition created by two or more processes and two or more resource locks
that keep processes from doing productive work.
Linux synchronization methods
Now that you have a little theory under your belt and an understanding of the problem to be
solved, let\'s look at the various ways that Linux supports concurrency and mutual exclusion. In
the early days, mutual exclusion was provided by disabling interrupts, but this form of locking is
inefficient (even though you can still find traces of it in the kernel). This method also doesn\'t
scale well and doesn\'t guarantee mutual exclusion on other processors.
The atomic operators are ideal for situations where the data you need to protect is simple,
such as a counter. While simple, the atomic API provides a number of operators for a variety of
situations. Here\'s a sample use of the API.
To declare an atomic variable, you simply declare a variable of type atomic_t. This structure
contains a single int element. Next, you ensure that your atomic variable is initialized using the
ATOMIC_INIT symbolic constant. In the case .
The Dining Philosopher Problem – The Dining Philosopher Problem states that K philosophers seated around a circular table with one chopstick between each pair of philosophers. There is one chopstick between each philosopher. A philosopher may eat if he can pick up the two chopsticks adjacent to him.
Semaphore = a synchronization primitive
higher level of abstraction than locks
invented by Dijkstra in 1968, as part of the THE operating system
A semaphore is:
a variable that is manipulated through two operations, P and V (Dutch for “test” and “increment”)
P(sem) (wait/down)
block until sem > 0, then subtract 1 from sem and proceed
V(sem) (signal/up)
add 1 to sem
Do these operations atomically
Repetition Control and IO ErrorsPlease note that the mate.docxsodhi3
Repetition Control and I/O Errors
Please note that the material on this website is not intended to be exhaustive.
This is intended as a summary and supplementary material to required textbook.
INTRODUCTION
Repetition control (also called loop control or just looping) is widely used in programming to reduce the
amount of simple sequential statements. File I/O errors are encountered when inputs (both file input and
user input) are not what the program expected.
THE while LOOP
With all looping mechanisms we will have a block of code (enclosed in curly braces) within the loop.
This block of code is called the body of the loop. The intention of the loop is to execute the same block
of code repetitively. Looping obviates the need to write overlong programs with the same statements
executed sequentially.
Some caution must be exercised when using the while loop, and these cautions all relate to the use of the
loop control variable or condition. The while loop has the following form:
while (loop_control_condition_is_true) {
// the statements in the body of the loop go
// here
}
Note that there is no semicolon (;) at the end of the loop block and that the body of the loop is contained
within curly braces. Note further the loop control condition is always evaluated at the top of the loop.
The number of times that the loop body is executed is determined by the use of the loop control
condition, which is a logical expression that must evaluate to true or to false. The loop body may be
executed 0 or more times. For instance, the body of the loop is not executed at all if the loop control
condition evaluates to false when the loop is encountered in your program. Usually, however, we want
the loop to execute at least once. If so, that brings us to the first important caution:
If you want the loop body to execute at least once, you must ensure that the loop control condition
evaluates to true when the while loop is encountered in your program. For example:
bool cond = true;
...
while (cond) {
...
}
Once we are sure that the loop body will execute at least once, we have to pay attention to the second
caution:
If you want to avoid an infinite loop (where the loop is never exited) you must ensure that the loop
control condition is made to evaluate false at some point within the body of the loop. For example:
const int MAX = 1000;
int i = 0;
...
while (i < MAX) {
...
i++;
}
The loop control condition can be a simple logical expression, or it can be a fairly complicated one. For
instance:
while (((i < MAX) && cond) || keep_going) ...
Using the KISS principle (Keep It Simple, Smarty) it is always advisable to keep the loop control
condition as simple as possible.
Some programmers are purists about loop control conditions, and believe the while loop should never be
exited except at the top of the loop (when the loop control condition becomes false). C++, however, has
two statemen ...
A brief introduction to Process synchronization in Operating Systems with classical examples and solutions using semaphores. A good starting tutorial for beginners.
Introduction to interprocess communication issues like race conditions and critical regions. Solutions such as mutual exclusion with busy waiting, sleep and wakeup, Semaphores, mutexes, monitors, barriers, and message passing.
Describe synchronization techniques used by programmers who develop .pdfexcellentmobiles
Describe synchronization techniques used by programmers who develop applications for
LUBUNTU (LINUX)
Solution
Concurrency and locking: Synchronization methods are necessary when the property of
concurrency exists. Concurrency exists when two or more processes execute over the same time
period and potentially interact with one another. The Linux kernel supports concurrency in both
modes. The kernel itself is dynamic, and race conditions can be created in a number of ways. The
Linux kernel also supports multiprocessing known as symmetric multiprocessing (SMP).
Concurrency can occur on uniprocessor (UP) hosts where multiple threads share the same CPU
and preemption creates race conditions. Preemption is sharing the CPU transparently by
temporarily pausing one thread to allow another to execute. A race condition occurs when two or
more threads manipulate a shared data item and the result depends upon timing of the execution.
Concurrency also exists in multiprocessor (MP) machines, where threads executing
simultaneously in each processor share the same data. Note that in the MP case there is true
parallelism because the threads execute simultaneously. In the UP case, parallelism is created by
preemption. The difficulties of concurrency exist in both modes.
To combat the issue of race conditions, the concept of a critical section was created. A critical
section is a portion of code that is protected against multiple access. This portion of code can
manipulate shared data or a shared service (such as a hardware peripheral). Critical sections
operate on the principle of mutual exclusion.
Race condition Situation where simultaneous manipulation of a resource by two or more threads
causes inconsistent results.
Critical section Segment of code that coordinates access to a shared resource.
Mutual exclusion Property of software that ensures exclusive access to a shared resource.
Deadlock Special condition created by two or more processes and two or more resource locks
that keep processes from doing productive work.
Linux synchronization methods
Now that you have a little theory under your belt and an understanding of the problem to be
solved, let\'s look at the various ways that Linux supports concurrency and mutual exclusion. In
the early days, mutual exclusion was provided by disabling interrupts, but this form of locking is
inefficient (even though you can still find traces of it in the kernel). This method also doesn\'t
scale well and doesn\'t guarantee mutual exclusion on other processors.
The atomic operators are ideal for situations where the data you need to protect is simple,
such as a counter. While simple, the atomic API provides a number of operators for a variety of
situations. Here\'s a sample use of the API.
To declare an atomic variable, you simply declare a variable of type atomic_t. This structure
contains a single int element. Next, you ensure that your atomic variable is initialized using the
ATOMIC_INIT symbolic constant. In the case .
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
2024.06.01 Introducing a competency framework for languag learning materials ...
UNIT III Process Synchronization.docx
1. UNIT – III
PROCESS SYNCHRONIZATION
What is Semaphore?
Semaphore is simply a variable that is non-negative and shared
between threads. A semaphore is a signaling mechanism, and a
thread that is waiting on a semaphore can be signaled by another
thread. It uses two atomic operations, 1) Wait, and 2) Signal for the
process synchronization.
A semaphore either allows or disallows access to the resource,
which depends on how it is set up.
Characteristic of Semaphore
It is a mechanism that can be used to provide synchronization
of tasks.
It is a low-level synchronization mechanism.
Semaphore will always hold a non-negative integer value.
Semaphore can be implemented using test operations and
interrupts, which should be executed using file descriptors.
Types of Semaphores
.
SEMAPHORE
COUNTING
SEMAPHORE
BINARY
SEMAPHORE
2. Counting Semaphores
This type of Semaphore uses a count that helps task to be acquired
or released numerous times. If the initial count = 0, the counting
semaphore should be created in the unavailable state.
However, If the count is > 0, the semaphore is created in the
available state, and the number of tokens it has equals to its count.
Binary Semaphores
The binary semaphores are quite similar to counting semaphores,
but their value is restricted to 0 and 1. In this type of semaphore,
the wait operation works only if semaphore = 1, and the signal
operation succeeds when semaphore= 0. It is easy to implement
than counting semaphores.
Counting Semaphore vs. Binary Semaphore
Counting Semaphore Binary Semaphore
No mutual exclusion Mutual exclusion
Any integer value Value only 0 and 1
More than one slot Only one slot
3. Provide a set of Processes It has a mutual exclusion mechanism.
The classical definitions of wait and signal are:
Wait: This operation decrements the value of its argument S,
as soon as it would become non-negative(greater than or equal
to 1). This Operation mainly helps you to control the entry of a
task into the critical section. In the case of the negative or zero
value, no operation is executed. wait() operation was originally
termed as P; so it is also known as P(S) operation.
The definition of wait operation is as follows:
wait(S)
{
while (S<=0);//no operation
S--;
}
Signal: Increments the value of its argument S, as there is no
more process blocked on the queue. This Operation is mainly
used to control the exit of a task from the critical
section.signal() operation was originally termed as V; so it is
also known as V(S) operation. The definition of signal
operation is as follows:
signal(S)
{
S++;
}
The classical problem depicting flaws of process synchronization in
systems where cooperating processes are present.
4. Three problems
1. Bounded Buffer (Producer-Consumer) Problem
2. Dining Philosophers Problem
3. The Readers Writers Problem
Bounded Buffer Problem
Because the buffer pool has a maximum size, this problem is often
called the Bounded buffer problem.
This problem is generalised in terms of the Producer
Consumer problem, where a finite buffer pool is used to
exchange messages between producer and consumer
processes.
Solution to this problem is, creating two counting semaphores
"full" and "empty" to keep track of the current number of full
and empty buffers respectively.
In this Producers mainly produces a product and consumers
consume the product, but both can use of one of the
containers each time.
The main complexity of this problem is that we must have to
maintain the count for both empty and full containers that are
available.
Dining Philosophers Problem
The dining philosopher's problem involves the allocation of
limited resources to a group of processes in a deadlock-free
and starvation-free manner.
There are five philosophers sitting around a table, in which
there are five chopsticks/forks kept beside them and a bowl of
rice in the centre, When a philosopher wants to eat, he uses
two chopsticks - one from their left and one from their right.
When a philosopher wants to think, he keeps down both
chopsticks at their original place.
The Readers Writers Problem
5. In this problem there are some processes(called readers) that
only read the shared data, and never change it, and there are
other processes(called writers) who may change the data in
addition to reading, or instead of reading it.
There are various type of readers-writers problem, most
centred on relative priorities of readers and writers.
The main complexity with this problem occurs from allowing
more than one reader to access the data at the same time.
Bounded Buffer Problem
Bounded buffer problem, which is also called producer consumer
problem, is one of the classic problems of synchronization. Let's
start by understanding the problem here, before moving on to the
solution and program code.
Problem Statement:
There is a buffer of n slots and each slot is capable of storing one
unit of data. There are two processes running,
namely, producer and consumer, which are operating on the
buffer.
Bounded Buffer Problem
A producer tries to insert data into an empty slot of the buffer. A
consumer tries to remove data from a filled slot in the buffer. As
6. you might have guessed by now, those two processes won't produce
the expected output if they are being executed concurrently.
There needs to be a way to make the producer and consumer work
in an independent manner.
Solution:
One solution of this problem is to use semaphores. The semaphores
which will be used here are:
m, a binary semaphore which is used to acquire and release
the lock.
empty, a counting semaphore whose initial value is the
number of slots in the buffer, since, initially all slots are
empty.
full, a counting semaphore whose initial value is 0.
At any instant, the current value of empty represents the number of
empty slots in the buffer and full represents the number of
occupied slots in the buffer.
The Producer Operation
The pseudocode of the producer function looks like this:
do
{
// wait until empty > 0 and then decrement 'empty'
wait(empty);
// acquire lock
wait(mutex);
/* perform the insert operation in a slot */
7. // release lock
signal(mutex);
// increment 'full'
signal(full);
}
while(TRUE)
Copy
Looking at the above code for a producer, we can see that a
producer first waits until there is atleast one empty slot.
Then it decrements the empty semaphore because, there will
now be one less empty slot, since the producer is going to
insert data in one of those slots.
Then, it acquires lock on the buffer, so that the consumer
cannot access the buffer until producer completes its
operation.
After performing the insert operation, the lock is released and
the value of full is incremented because the producer has just
filled a slot in the buffer.
The Consumer Operation
The pseudocode for the consumer function looks like this:
do
{
// wait until full > 0 and then decrement 'full'
wait(full);
// acquire the lock
wait(mutex);
8. /* perform the remove operation in a slot */
// release the lock
signal(mutex);
// increment 'empty'
signal(empty);
}
while(TRUE);
Copy
The consumer waits until there is atleast one full slot in the
buffer.
Then it decrements the full semaphore because the number of
occupied slots will be decreased by one, after the consumer
completes its operation.
After that, the consumer acquires lock on the buffer.
Following that, the consumer completes the removal operation
so that the data from one of the full slots is removed.
Then, the consumer releases the lock.
Finally, the empty semaphore is incremented by 1, because
the consumer has just removed data from an occupied slot,
thus making it empty.
Dining Philosophers Problem
The dining philosophers problem is another classic
synchronization problem which is used to evaluate situations where
there is a need of allocating multiple resources to multiple
processes.
9. Problem Statement
Consider there are five philosophers sitting around a circular dining
table. The dining table has five chopsticks and a bowl of rice in the
middle as shown in the below figure.
Dining Philosophers Problem
At any instant, a philosopher is either eating or thinking. When a
philosopher wants to eat, he uses two chopsticks - one from their
left and one from their right. When a philosopher wants to think, he
keeps down both chopsticks at their original place.
Solution
From the problem statement, it is clear that a philosopher can
think for an indefinite amount of time. But when a philosopher
10. starts eating, he has to stop at some point of time. The philosopher
is in an endless cycle of thinking and eating.
An array of five semaphores, stick[5], for each of the five chopsticks.
The code for each philosopher looks like:
while(TRUE)
{
wait(stick[i]);
/*
mod is used because if i=5, next
chopstick is 1 (dining table is circular)
*/
wait(stick[(i+1) % 5]);
/* eat */
signal(stick[i]);
signal(stick[(i+1) % 5]);
/* think */
}
Copy
11. When a philosopher wants to eat the rice, he will wait for the
chopstick at his left and picks up that chopstick. Then he waits for
the right chopstick to be available, and then picks it too. After
eating, he puts both the chopsticks down.
But if all five philosophers are hungry simultaneously, and each of
them pickup one chopstick, then a deadlock situation occurs
because they will be waiting for another chopstick forever. The
possible solutions for this are:
A philosopher must be allowed to pick up the chopsticks only
if both the left and right chopsticks are available.
Allow only four philosophers to sit at the table. That way, if all
the four philosophers pick up four chopsticks, there will be
one chopstick left on the table. So, one philosopher can start
eating and eventually, two chopsticks will be available. In this
way, deadlocks can be avoided.
What is Readers Writer Problem?
Readers writer problem is another example of a classic
synchronization problem. There are many variants of this problem,
one of which is examined below.
The Problem Statement
There is a shared resource which should be accessed by multiple
processes. There are two types of processes in this context. They
are reader and writer. Any number of readers can read from the
shared resource simultaneously, but only one writer can write to
the shared resource. When a writer is writing data to the resource,
no other process can access the resource. A writer cannot write to
the resource if there are non zero number of readers accessing the
resource at that time.
The Solution
12. From the above problem statement, it is evident that readers have
higher priority than writer. If a writer wants to write to the resource,
it must wait until there are no readers currently accessing that
resource.
Here, we use one mutex m and a semaphore w. An integer
variable read_count is used to maintain the number of readers
currently accessing the resource. The variable read_count is
initialized to 0. A value of 1 is given initially to m and w.
Instead of having the process to acquire lock on the shared
resource, we use the mutex m to make the process to acquire and
release lock whenever it is updating the read_count variable.
The code for the writer process looks like this:
while(TRUE)
{
wait(w);
/* perform the write operation */
signal(w);
}
Copy
And, the code for the reader process looks like this:
while(TRUE)
{
14. }
Copy
Here is the Code uncoded(explained)
As seen above in the code for the writer, the writer just waits
on the w semaphore until it gets a chance to write to the
resource.
After performing the write operation, it increments w so that
the next writer can access the resource.
On the other hand, in the code for the reader, the lock is
acquired whenever the read_count is updated by a process.
When a reader wants to access the resource, first it
increments the read_count value, then accesses the resource
and then decrements the read_count value.
The semaphore w is used by the first reader which enters the
critical section and the last reader which exits the critical
section.
The reason for this is, when the first readers enters the critical
section, the writer is blocked from the resource. Only new
readers can access the resource now.
Similarly, when the last reader exits the critical section, it
signals the writer using the w semaphore because there are
zero readers now and a writer can have the chance to access
the resource.