Parallel Programming and Algorithms Guide
Parallel Programming and Algorithms Guide
Course objectives
The objectives pursued in the context of this course on Algorithmics and Parallel Programming
are presented as follows:
1. Allow students to acquire basic concepts in parallel and distributed computing.
2. Study and analyze parallel algorithms
3. Design and deploy parallel programs for workstation networks, clusters and
global computing
Prerequisites
In order to ensure a good understanding of this course, students are expected to have
solid knowledge in the following fields and languages:
Linux operating system
2. Language C (C++, Fortran, Java)
3. Notions of complexity
4. Management of Competition
Course summary
1. Generalities on parallelism
2. Parallel Programming Models
3. Parallel programming with MPI
4. Parallel scientific libraries
5. Grid computing
Chapter 1
Generalities on parallelism
1.1. Motivation and definition of a distributed system
1.1.1. Motivation
Computer Science of 1946 with the construction of the ENIAC (Electronic Numerical Integrator And
Computer) composed of 19000 tubes, weighing 30 tons, with a clock speed of 100 KHz, does not
nothing to do with current Computing where micro-computers reach speeds
above 3 GHz for less than ten kilograms. The use of a computer has become
almost indispensable in everyday life. However, despite the omnipresence, see
Despite the omnipotence of computers, there are still and always needs for computing power.
superior to the capabilities of current machines.
The needs for computing power (and even storage) are increasing in a
a multitude of domains (simulation and modeling, signal processing, image processing, data mining,
drug design, molecular biology, web page ranking etc.) and the
Parallelism is an attempt at an answer that is still relevant today. This is the purpose for which they were designed.
Currently, these different types of machines coexist and the fleet of universities and
companies are often very heterogeneous, comprising supercomputers, clusters (groups of
computers) and personal workstations. However, these different machines are not sufficient.
always to solve increasingly complex problems. Networks are becoming increasingly
Rapidly, the current trend in parallel and distributed computing is to seek to federate a
set of these machines, distributed across a continent, or even the entire planet, in order to
aggregate computing power. This is the famous computing grid (Grid computing) (figure 1.1).
The new type of computing platform is very heterogeneous, whether at the level of
computing resources (processors) or at the level of communication capabilities (network). The consideration of
Accounting for this heterogeneity is therefore a major challenge for the effective use of platforms.
of today and tomorrow.
increasing the number of workers no longer brings any time gain. In fact,
Some tasks are purely sequential and can only be performed by one person.
Par exemple, deux marathoniens ne peuvent se partager la distance à parcourir et réclamer la médaille
of gold.
It is naturally that the concept of parallelism has been applied to computers. As a result, it
it has been possible to meet the power needs required for the realization of projects
consumers in terms of calculations and memory size. In fact, parallelism can be defined
as a technique for enhancing the performance of a computer system based on
the simultaneous use of multiple resources (processor, memory, hard disk, ...). This means
that will require breaking down the problem to be solved into several sub-problems that can be
resolved concurrently by several processors.
Algorithms are fundamental in the search for a solution through computer means.
because one must give a computer a series of clear instructions to lead to a solution
in a reasonable time. Programming a computer requires more than just a simple translation
well known instructions in a language understandable by the computer.
Combined parallelism with efficient algorithms allows for saving time in order to
best respond to important needs. It breaks with the classic approach that involves winning
the speed by performing each operation more quickly, is bounded by the laws of physics.
Let us also mention the intrinsically parallel nature of certain problems that will gain clarity.
to be programmed according to a parallel model providing the appropriate constructions. Finally, let us note the
Let us consider the following sequential program that calculates a vector of polynomials.
pouri = 0àn-1making
vv[i] = a + b.v[i]² + c.v[i]3+ d.v[i]4+ e.v[i]5+ f.v[i]6+ g.v[i]7
end for (VP)
The instances of the body of the loop of the problem (VP) can execute independently.
one another:
pour = 0 to do in parallel
vv[i] = a + b.v[i]² + c.v[i]3+ d.v[i]4+ e.v[i]5+ f.v[i]6+ g.v[i]7
end for
Note that in data parallelism, the data is often more numerous than the
number of processors. This raises the issue of load distribution between the processors. For this
Data distribution can be done in three different ways: by block, cyclically, or by blocks.
cyclic
Here, parallelism is limited to three processes. The processors must synchronize at the end.
of a calculation.
In the data parallel programming model, the flow of control is unique and each
instruction is executed on a dataset arranged on a virtual geometry. This
Geometry is defined by an abstract description of a virtual processor grid. The complexity
The calculation and communication of a data-parallel algorithm varies depending on the strategy of the
data distribution. The choice of data distribution is related to the choice of the
geometry used. As a result, the choice of geometry becomes an important parameter to consider
taken into account in this type of programming model. HPF and CM Fortran are two typical examples
parallel data programming languages. This programming model is well suited for
SIMD machines like CM-2 or CM-200.
1
multithread programming model
directly the thread library defined in the Posix standard. This programming model is well
adapted to MIMD machines of the shared memory type such as IBM SP3 or IBM SP4.
can be blocking. The emission can be non-blocking if the network interface can move it
even the data, or whether the processor can be interrupted later to move the data.
Finally, if the emission is non-blocking with a network that cannot retain messages, we obtain
an unstable communication.
According to Dekeyser and Marquet, any language that can be called a data-parallel language
in which an instruction involves several identical processes on the data of a set.
Data parallelism offers the programmer defined primitives on sets (vectors
and matrices most commonly), which translates into duplicating the processing as many times as there
of data in the specified structure.
2
The ways to transfer private data between processors vary according to the architecture of the parallel machine.
While different ways to program a sequential machine can be found, the uniqueness of
however limits the models that could be associated with it. Thus, the 'optimal' model
is quickly found. The parallelism, on the contrary, has greatly multiplied the possibilities:
Number of processors,
Arrangement,
Communication network
•Shared or distributed memory,
Centralized or distributed control,
etc
The quest for the optimal model in parallelism is still a subject of research. In fact,
the analyses agree that a single model is an illusion, given the diversity of problems and
the machines (or models) to solve them is large.
The notion of parallelism has greatly contributed to the multiplication of computational models.
1.6.1. User time (wallclock time) and computation time (cpu time)
Let P=4 be the number of processors. Let's imagine that the execution time of a program is
4 minutes if it is handled by only one processor.
If we use the 4 processors to perform the same task, each processor should in
principle work 1 minute to do your share of the work.
If no communication is necessary, all processors have effectively completed their task.
after 1 minute. This is the ideal case: the wall clock time is 4 times smaller than that of the serial execution.
The CPU time is however the same (4 processors worked for 1 minute: in total, there are 4)
work minutes.
Unfortunately, some communications are still necessary. These communications
extending the time necessary for each processor to complete its share of the work.
Each processor will therefore work for more than a minute (let's say 1 min 15 sec). Even if we
using 4 processors, we do not get the final result in 4 times less time. The wallclock time is
greater than a quarter of that of serial execution. Moreover, the CPU time has increased (4
Processors worked for 1 min 15 sec: in total there is now 5 minutes of work.
Let's suppose that in the previous example one of the four processors is twice as slow as
the other three. It will take him 2 minutes and 15 seconds to complete his part of the work. The other three processors
will have worked for 1 minute 15 seconds and then will have remained 1 minute doing nothing (CPU is idle). The user
Wait 2 minutes 15 seconds to get your result. The wall clock time is therefore more than half of that.
of a serial execution.
The situation is worse than if we had only worked with the other three processors. In
Indeed, the wall clock time would have been 4 min / 3 + 15 sec = 1 min 35 sec. To use it exactly the
the slowest processor actually needs to be given half the work of the other three. We
this touches on the issue of workload distribution (load balancing).
Where should we parallelize? At the highest level (processing the parts in parallel)? Or at the level
plus bas (traiter en parallèle les sous-sous-parties)?
Parallelizing at the highest level reduces communication times, but the work is at risk.
to be poorly distributed if the parts do not all have the same execution time.
Parallelizing at the lowest level increases communication times, but the work is
better distributed among the processors.
We recommend letting the compiler handle the lowest levels and
parallelize your program at the highest level.
Parallelism has not only advantages. Thus, we can note the following dangers related to
in parallelism:
1. Rounding errors can depend on how the work is distributed. The results of a code
Parallelized ones are not always identical to those of a sequential program.
2. If multiple processors access the same data, undesirable effects can occur if these
data is modified by a processor and if others continue to work with an old one
version of these.
The process by which each processor has at each
instant of the same shared data copy. This update operation is resource-intensive
communications and reduce the effectiveness of parallelization.
3. Opening files by several processors at the same time can also cause problems.
(notably during parallelization with OpenMP or MPI). It is then necessary to keep up to date a
shared variable that indicates at every moment whether a file is being manipulated or not. A
The processor is only allowed to open a file if it is the only one doing so.
Before opening a file, a processor must therefore check the status of this variable and
to wait for it to take a value indicating that no other processor is handling the file. It
then change the state of this variable, manipulate the file, and restore the variable to its initial state.
allowing other processors to manipulate files.
4. When the work of one processor requires that of another to be completed, it is again
necessary to keep him waiting.
Chapter 2
The problems related to parallelism can be approached from both a software and
material:
1. Determination of competition (parallel algorithm or 'software') through evaluation of the
granularity (refers to the number of calculations, instructions, or elementary operations), implementation in
mechanism for control ensuring the execution of programs (synchronization) and the
data management (geometry of communications).
2. Projection ('mapping') of parallel algorithms on specific machines (architectures
parallels or "hardware": complexity of the elementary computing entity, operating mode,
memory distribution and interconnection network.
3
Symmetrical Multi Processors also known as shared memory multi processors systems
4
also called shared nothing
There are also non-uniform memory access (NUMA) architectures. 5) and architectures
hierarchical.
Unlike SMP architecture, non-uniform memory architectures do not offer a
uniform cost of memory access. This type of architecture allows for global addressing for the
distributed memories (the local memory of each processor). This global addressing can be located
either at the hardware level or at the software level. Each processor has its own memory
The local accesses other memories via an interconnection network. This network can be made up of a
hierarchical bus structure. In this case, the access time to memory depends on the number of buses
crossed. Generally speaking, the bandwidth of this type of network increases depending on the
number of processors, allowing for better scalability of the NUMA architecture (some
hundreds of processors) compared to the SMP architecture. The SGI Origin 2000 machines,
Onyx 3000, Compaq GS Series Alpha Server are representative examples of NUMA architecture.
5
Non Uniform Memory Access
part of the flexibility provided by shared memory. It allows the interconnection of a large
number of shared memory nodes, which can themselves be powerful multiprocessors. In
Each node's communications between the processors are efficiently done thanks to the memory.
shared.
Routing determines the path to take in the network to go from a source processor to a
destination processor. The communication mode indicates how the messages are
transported.
We distinguish the following modes:
Circuit switching: before sending its message, the source sends a request.
to the destination in order to build an end-to-end physical circuit. Once the
circuit established, the message is then transmitted directly to the destination,
Packet switching: each router has memory buffers, each of which can
store a packet. Upon receiving a packet, the router stores it in one of
buffers before forwarding it to the next router on the packet's route. Each packet
contains information allowing the router to calculate the path to follow,
"Whormhole": the message is divided into small entities called "flits" that are
stored in the memory buffers of routers. Only the first 'flit' contains
information that allows the router to calculate the path to follow, while the others
"flits" contain only data. They must therefore proceed one after the other.
others in the network.
There are several types of classifications of parallel machines. The classical classification
Flynn's classification is based on the notions of control flow and data flow.
Flynn's taxonomy presents four types of parallel machines: SISD, SIMD, MISD, and MIMD.
1. SISD machine. A SISD (Single Instruction stream Single Data) machine is what we
usually calls a sequential machine, or Von Neumann machine. A single
instruction is executed at a given time and a single piece of data (simple, unstructured) is
treated at every moment.
2. MISD machine. A MISD (Multiple Instruction stream Single Data) machine can execute
several instructions at the same time on the same data. This may seem paradoxical but
this actually covers a very ordinary type of micro parallelism in microprocessors
modern: vector processors and pipeline architectures.
3. Machine SIMD. In a SIMD (Single Instruction stream Multiple Data) machine, each
the instruction of a program is executed identically on each processor, but on some
different and private data to each processor. In other words, in this type of machine,
The parallel execution of the same instruction occurs simultaneously on processors.
different. In general, it has a large number of processors. The CM-200 computers,
CM5, Hitachi S3600, CPP DAP Gamma II, and Alenia Quadrics were among the first
examples of parts of SIMD machines.
Systolic machines are special SIMD machines in which the
calcul moves across a topology of processors, like a wave front, and acquires
local data changes with each wave front movement (comprising several
processors, but not all in general).
In both cases, the parallel execution of the same instruction is done at the same time on
different processors (synchronous data parallelism).
4. MIMD machines. The case of MIMD (Multiple Instruction stream Multiple Data) machines is
the most intuitive. Here, each processor can execute a different program on data
different. We have several possible types of architecture:
Shared memory
Local memory + communication network (Transputer, Connection Machine) - System
distributed.
Notons SPMD is a special case of the more general MPMD model (Multiple Program,
Multiple Data), which it can also emulate .
Parallel algorithms are an approach that has allowed the development of models enabling
to solve a large number of problems. These models can be classified into two main families
what are: fine-grained models and coarse-grained models.
Fine-grained models were the first parallel models to appear. The notion of grain
comes from the fact that, for these models, it is assumed that the number of processors is essentially
equal to the number of input data.
The two main families of fine-grained models are: memory machine models
shared and distributed memory machine models.
This model is further specified by defining the access mode to memory. Four variants
are the most often used:
- Exclusive-Read Exclusive-Write (EREW) PRAM: in this variant, two processors do not
can access the same memory location simultaneously whether to read or
good for writing,
Concurrent-Read Exclusive-Write (CREW) PRAM: this variant allocates more than one
processor for reading but not for writing in the same memory location at the same time
weather
Concurrent-Read Concurrent-Write (CRCW) PRAM: for this variant, it is possible
for multiple processors to access the same memory location to read or to
to write
- Exclusive-Read Concurrent-Write (ERCW) PRAM: this variant has a very
restricted applications.
The advantage of this model is its simplicity. Moreover, it is very useful for highlighting parallelism.
studied problems. It is often a first step towards parallelization.
Given its high level of abstraction, it allows us to know to what extent a problem
may be parallelized or not. However, it is greatly removed from real machines. Furthermore, the
technological constraints do not allow a large number of processors to access a
common memory in constant time. That is why there is no PRAM machine today; to
memory is distributed among the processors.
In this model, each processor has its own constant-size local memory and there is no
no shared memory. The processors can only communicate through an RI. Like in
In PRAM, the processors work synchronously. At each step, each processor can
simultaneously send a data word to one of its neighbors, receive a data word from one of its
neighbors and perform a local operation on its data.
Each distributed memory model explicitly takes into account the topology of the network.
interconnection represented by different characteristics:
the degree, which is the maximum number of neighbors for a processor. It corresponds to a
sort of architectural limitation given by the maximum number of physical links
associated with each processor,
the diameter, which is the maximum distance between two processors (the distance being the most
short path in the interconnection network between these two processors). It provides a
lower bound on the complexity of algorithms in which two processors
arbitrariness must communicate,
the bisection, which is the minimum number of links to remove in order to disconnect the network
two networks of the same size (give or take one processor). It represents a
lower bound on the execution time of algorithms where there is a phase that does
communicate half of the processors with the other half.
Among these distributed memory models, the two-dimensional grid and the hypercube have been
widely used. More recently, other interconnection networks have emerged such as the
honeycombet its extension called star-honeycomb, or also leXmesh.
The specificity of the algorithms developed on distributed memory models (if possible
effective or even optimal) is a major drawback. Thus, these algorithms are not portable because
They are heavily dependent on the chosen topology.
c. Systolic model
like a heart playing the role of a pump on several crossing streams. The regular rhythm of these
processors maintain a constant flow of data throughout the network.
This model appears when VLSI and WSI technologies have emerged and its success relies on
large part of its adaptation between the demand for extremely fast low-cost calculators and the
possibility of significantly reducing the execution time of several sequential algorithms
At the simple price of an increase in the complexity of the material through the replication of structures.
Since then, significant efforts have been made to design parallel architectures based
on the regularity of the data rhythm ('dataflow architectures'), to pipeline the
processors or vectorize them, or on the regularity of the execution flow ('wavefront architectures'). The
The main problem of developing such computers lies in the organization of intensive flows.
control and data ensuring high performance. The pipelined architectures and
"wavefront" are systolic variants that are among the most effective. They have thus largely
contributed to the dissemination of the systolic model and to its familiarization.
Most of the machines currently used are large data grain, which means that the
the size of each local memory is much larger than the size of a data item. Thus, from
Numerous studies have described models that take into account the real characteristics of
machines. These models recognize, for example, the existence of communication costs,
unlike the PRAM model, without specifying the topology of the support of
communications, unlike fine-grained models of distributed memory.
The BSP model ('Bulk Synchronous Parallel'), the first model of its kind proposed by Valiant,
formalize the architectural characteristics of existing machines through four parameters.
The LogP model described by Culler et al. specifies more parameters than BSP, while CGM
"Coarse Grained Multicomputers" proposed by Dehne et al. is a simplification of BSP.
The parallelization of a problem depends on the nature of the problem as well as the architecture.
Material considered. However, the general philosophy is represented in figure 2.5.
2. Avoid cluttering your loops with instructions that may lead the compiler to think that
iterations are not independent. For example, avoid this:
6
A condition to use autoparallelization options at compile time
If your IT infrastructure allows you to run multiple executables at the same time, you
you can parallelize your problem by assigning each machine the calculations corresponding to a part
of this problem. The idea here is to parallelize the task to be done rather than the program itself. This
last indeed must not undergo any modification.
Note that the assignment of tasks to processors poses a scheduling problem.
Example:
You have 20 machines and you need to compute a function on a grid of 100 points.
Just assign the calculation of 5 points to each machine. Rather than parallelizing your program,
The idea here is to plan 20 tasks that will execute the same sequential program on inputs.
different. Once the 20 tasks are completed, you just need to collect
the partial results.
What to do if all machines are identical? We must avoid entrusting the machines with
too slow too much work under the penalty of having to eventually wait for them. The idea is to entrust each
machine the right amount of work, so that they all finish at the same time.
To set things straight, let's assume we have 10 additional machines, 3 times slower.
that the first 20. We have 100 calculations to complete, which take one minute each on the
the fastest machines and therefore 3 minutes on the slowest.
Let N=100 be the number of calculations to be performed, N1the number of fast computers, N2=10 the number
slow computers. Let's call v1=3 the speed of fast machines and v2the speed of machines
glasses. We are looking for the number n1calculations to assign to each fast machine and the number n2of
calculations to be entrusted to each slow machine.
n1.N1+ n2*N2=N
n1/v1= n2/v2
We find:
v1.N 3.100
n1= = 4.2857...
v1.N1+v2.N23.20 + 10
v2.N 1.100
n2= = 1.4285...
v1.N1+v2.N23.20 + 10
All the machines will finish their task at the same time if we assign each of them this
number of calculations. As these numbers are fractional, some of the slow machines will receive in
reality 1 calculation to be made, others 2. The latter therefore receive too much work and will be delayed.
the end of the process. They will indeed need 2 * 3 = 6 minutes to complete their task, whereas 5
minutes were sufficient by only working with the fastest machines. We see that this model
give an approximation of the number of calculations to assign to each processor, but do not give the
optimal name.
In the previous example, only one task should have been assigned to the most...
lenses2and leave what remains to the fastest computers. The new idea is not to entrust
a task to a slow processor only after all the fast processors have already received 3
tasks. Only then do slow processors become useful and stop making us wait.
end of the procedure.
The initial distribution of tasks is then done gradually (see figure 2.6). The v1.N1=60
the first calculations are entrusted to the 20 fast processors. The v2.N2The following 10 calculations are then
entrusted to the 10 slow computers. And we start again like this: the v1.N1=60 calculations that follow are entrusted to
fast computers. A second calculation is only entrusted to slow computers if each computer
Rapide has already received 6 tasks (these will be tasks 131-140).
o returning to the first box if this condition is not met or if we arrive at all
right
Beware of conflicts.
Very little overhead from parallelization.
Most often, the number of processors < 32.
Expensive architecture.
The latest model is one where the processors do not have access to a common memory area.
but have only a private memory, visible only to them (distributed memory). The
processors must communicate explicitly with each other to transmit information.
The MPI (Message Passing Interface) library allows for controlling all these communications. We
We will explore it further in chapter 3.
Cheap architecture.
In parallel complexity, we have two parameters to manage: N and P. Two cases can be
produce:
a) If N is greater than P, we place several elements on the same processor and process them.
in sequence (also called concurrently). In this method known as virtual processors, the
Processor switching can take time: if this time is a constant that does not depend on
If it is not P, then it does not affect the asymptotic complexity. Conversely, the loss of
performance can be important.
b) If N is smaller than P, we cannot use all the processors; in this case, only
effectiveness is affected.
In practice, the size of the problem is generally much greater than the number of processors: N >> P.
Demonstration:
Let f be the fraction of the code that is parallelizable and P be the number of processors.
Interpretation:
Intermediate cases:
{"Conclusions":"Conclusions"}
• S(P) eventually reaches saturation (the later it happens, the closer f is to 1).
• This ideal case is more easily approached by parallelizing at the highest level and where the
program spends the most time.
Performing a parallel computation means having several processors cooperate to carry out a calculation.
Advantages:
Speed:
For N processors, computation time divided by N, in theory.
2. Memory size:
For N processors, we generally have N times more memory.
Difficulties:
One must manage the division of tasks.
It is necessary to manage the exchange of information (non-independent tasks)
Chapter 3
Parallel programming with MPI
3.1 Introduction
The model of parallelism considered in this chapter is one where the processors have
only a private memory, visible only to them (distributed memory). There is no memory here
shared and all information exchange between processors is done via messages that must be
explicitly programmed. The MPI (Message Passing Interface) library provides the instructions that
allow to schedule these information exchanges.
A message is made up of data packets (variables, scalars, arrays, etc.) passing through
from the sender process to the receiver process(es). In this environment, if a message is sent to
a process, it must then receive it (see figure 3.2). The receiving process must be able to
classify and interpret the messages that have been addressed to him.
In certain programming models, a particular thread (the Master) is sometimes entrusted with
who has the number 0) the task of distributing/collecting the data. The other threads (the Slaves)
they do the work.
Asynchronous messages: Communication ends as soon as the message is sent. The sender
just know when the message has been sent.
[Link] messages: The sender cannot do anything during the message sending.
[Link]-blocking messages: The sender can perform other tasks while sending the message.
Operations:
• Barrier: wait for all processors to reach the same point in the program
• Reduction: we take data from each processor, we reduce them to a single data point.
which is then made available to all processors
When using blocking messages without caution, it can happen that all threads get
find themselves in a state of perpetual waiting (deadlock).
Example: If all the threads send a blocking message at the same time: they all end up at
await a confirmation of receipt of their message while none of them are able to
to intercept it.
# include<stdio.h>
{
int myid, numprocs;
/*MPI Initialization*/
MPI_Init (&argc,&argv);
MPI_Comm_Rank (MPI_COMM_WORLD,&myid);
if (myid == 0)
Quit mpi
MPI_Finalize ();
Result:
My number is 1
My number is 0
My number is 2
A so-called point-to-point communication takes place between two processes, one called process
emitter and the other process receiver (or recipient).
The sender and the receiver are identified by their rank in the communicator.
The part we call the envelope of a message is made up of:
1. the rank of the emitting process;
the rank of the receiving process;
3. of the message tag;
4. the name of the communicator who will define the communication context of
the operation.
The exchanged data is typed (integers, reals, etc. or personal derived types).
There are several transfer modes in each case, using different protocols.
MPI_STATUS_SIZE status;
...
where is the information to be transferred, size its size and type its type. source and destination are the numbers
from the transmitter and the receiver. Tag the message number or label. The status table
(MPI_STATUS_SIZE) allows to know afterwards if the communication is finished.
oùrequestest un entier qui permet de savoir par la suite si la communication est terminée.
Blocking buffered send: the message is stored in a buffer before being sent.
MPI_BUFFER_ATTACH(buffer, size)
MPI_BSEND(data, size, type, destination, tag, MPI_COMM_WORLD)
MPI_BUFFER_DETACH(buffer,size)
where buffer is the buffer variable in which data is transferred before communication.
• Blocking reception:
wheresourceis the transmitter number (or MPI_ANY_SOURCE) andtagis the message number
(ouMPI_ANY_TAG).
• Non-blocking reception:
where request is an integer that allows to know later if the communication is finished.
MPI_WAIT(request,status)
# include<studio>
# include<mpi.h>
int main(int argc, char *argv[])
{
int rank, size;
MPI_Status status;
Hello from processor 0
char RecvMsg[23];
int root;
int tag;
int rankdest;
int i;
/* initialization */
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
sending the message
root = 0;
if (rank==root)
for(i=1;i<size;i++)
{
tag=i;
rankdest=i;
MPI_Send(SendMsg, 23, MPI_CHAR, rankdest, tag, MPI_COMM_WORLD);
}
/* receipt of the message */
RecvMsg=SendMsg;
if(rank!=root) {
tag = rank;
MPI_Recv(RecvMsg, 23, MPI_CHAR, root, tag, MPI_COMM_WORLD, &status);
printf("I am processor %d, I received the message: %s \n", rank, RecvMsg);
}
MPI_Finalize();
}
MPI_TESTALL(count,array_of_requests,flag,array_of_statuses)
MPI_BARRIER(MPI_COMM_WORLD)
To distribute information from the thread source to all other threads, one can use:
# include<stdio.h>
# include<mpi.h>
int main(int argc, char *argv[])
{
int range, value;
/* initialization */
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Finalize();
}
Execution:
To split information held by the thread source and distribute its parts to others
threads, we can use:
where data_to_send is the information to be distributed and size_to_send is the size of the chunks to be sent to each
threads. These pieces are placed by each thread in data_to_recv, which has a size of size_to_recv.
type_to_send and type_to_recv describe the types of messages. If type_to_send = type_to_recv, then size_to_send
= size_to_recv.
The opposite operation consists of gathering the fragments held by each thread to
give the thread the complete information:
where data_to_send is the piece of information contained by each thread, size_to_send is its size,
data_to_recvla variable qui contiendra tous les morceaux,size_to_recvla taille des morceaux reçus.
If type_to_send = type_to_recv, then size_to_send = size_to_recv.
To give each thread i the i-th part of each fragment, we can use this sub-
routine
MPI_COMM_WORLD)
where data_to_send is the information contained by each thread on which the operation must be
executed. The result appears in the variable data_to_recv from the source thread.
The main predefined reduction operations (there are also other logical operations)
are summarized in the table below.
To ensure that each thread receives the result of the operation, we can use:
3.6.3 Reduction operations with partial results communicated to the various threads (scan)
With the subroutine scan, each thread receives the result of the operation performed on its
element and that of the threads that precede it.
Reminder: the trace of a matrix is the sum of the elements of its diagonal (matrix
necessarily square)
Immediately, it is easy to see that the problem can be parallelized by calculating the sum
diagonal elements on multiple processors then using a reduction to calculate
the global trace
#include <stdio.h>
#include <mpi.h>
double A[N][N];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &me);
MPI_Comm_size(MPI_COMM_WORLD, &np);
tranche = N/np;
/* Initialization of A done on 0 */
/* … */
if (me == 0) {
buffer[i] = A[i][i];
The scatter operation allows distributing the buffered diagonal among the processes.
trace_loc = 0;
trace_loc += diag[i];
if (me == root)
MPI_Finalize();
The MPI-2 standard introduces some new features to address certain gaps observed.
allows among other things, the dynamic management of the number of processors.
For the use of MPI under Windows, it is recommended to use MPICH. This
installation requires including certain things in PATH and copying certain files into the
compiler's lib directory used.
Chapter 4
If it is long and difficult to write generic subprograms for numerical analysis, which
the more efficient they are, the difficulty is multiplied if it concerns doing it for machines with memory
repartition. Here too, we have every interest in checking beforehand if it does not exist in a library or
library.
The major benefit of using libraries (aside from the saved work!) comes from this
that allow for combining portability and performance - except in the particular case of non
portability of certain parts of the manufacturers' libraries.
They indeed account for a wide range of factors, almost outside
of reaching by non-specialists:
• independence regarding the type of data (simple or double precision real?, real or
complexes ?)
•independence regarding data representation (symmetric matrices, bands,
hollows ?) ;
the choice of the best numerical algorithm;
the verification of the numerical stability of the algorithm;
optimization based on the architecture of the target machine;
Optimization based on the case to be handled (a matrix product is programmed differently)
according to the ratio between the number of rows and columns of these.
library ((P)ESSL at IBM, SSL2VP(P) at Fujitsu, ASL and MathKeisan at NEC, SciLib
at Cray, etc.) ;
their advantage is that they have (in principle!) optimal performance for the
machines concerned;
However, they are not portable.
Note that several of the libraries presented in this chapter are not accessible, or
mostly accessible, whether in C or Fortran. It will therefore be necessary for some
programmers to develop the expertise to mix compiled objects in C and others
compiled in Fortran.
4.2. PBLAS
4.2.1. BLAS
Started in 1978, BLAS (Basic Linear Algebra Subroutines) is a library for performing
elementary operations of linear algebra but in a relatively optimized way. Several others
libraries and font references. The BLAS_LEVEL_1, BLAS_LEVEL_2, and BLAS_LEVEL_3 perform
respectively of vector-vector, vector-matrix, and matrix-matrix operations.
4.2.2. PBLAS
PBLAS (Parallel BLAS) (Parallel Basic Linear Algebra Subprograms) defined and implemented in the
framework of the ScaLAPACK project (during the second major modification of this library, but which has
gave rise to the first public version), in analogy with what was done for LAPACK, which did
a wide use of BLAS.
Provides on distributed memory machines everything (or almost everything) that BLAS provides
1, 2 and 3 on shared memory machines.
Interface as close as possible to that of BLAS. PBLAS uses BLACS for the
communications.
4.3. ScaLAPACK
4.3.1. BLACS
Written in C, BLACS is often based on MPI, but not necessarily (on IBM, LAPI, which
is the native communication layer on these machines). The call syntax for BLACS remains
identical from one system to another (hence its relevance).
4.3.2. LAPACK
4.3.3. ScaLAPACK
Project started in 1989 under the responsibility of Jack Dongarra (University of Tennessee and
Oak Ridge Laboratory.
The ScaLAPACK project (Scalable Linear Algebra PACKage) itself is actually divided
today in four components:
1. the ScaLAPACK library: linear algebra for dense matrices;
2. the PARPACK library (Parallel ARPACK): searching for certain eigenvalues on very
large matrices
3. the CAPSS library (CArtesian Parallel Sparse Solver): solving linear systems on
symmetric positive definite sparse matrices, by direct method;
4. the PARPRE library (PARallel PREconditioners): a set of preconditioners for the
handling of any sparse matrices.
Since version 1.0 from February 95, which was the first public version, it is based on the
PBLAS and BLACS libraries.
The main areas addressed are:
1. resolution of linear systems and factorization (LU, Cholesky, QR, etc.);
2. matrix inversion;
3. systems with eigenvalues.
Project launched in late 2004 (through new funding granted by the NSF in the United States), for
develop a new version of ScaLAPACK (and LAPACK), integrating the advancements
algorithmic in recent years
4.4. Super_LU_DIST
4.4.1. Super_LU
4.4.2. Super_LU_DIST
4.5. PETSc
Developed by the Argonne National Laboratory, PETSc (Portable, Extensible Toolkit for
Scientific Computation) is a library made up of a set of procedures that allows
solve both sequentially and in parallel partial differential equations and problems
linear algebra (linear and nonlinear equations) using iterative numerical methods based on
on Krylov subspaces. PETSc uses MPI for inter-process communications.
Portable across various environments including those of Cray, HP, IBM, NEC, SGI, Sun, etc. It can be
used directly by Fortran, C or C++ programs.
4.6. P_ARPACK
4.6.1. ARPACK
4.6.2. P_ARPACK
P_ARPACK (Parallel ARnoldi PACKage) does the same thing as ARPACK but in execution
parallel.
•Vectors (Vec): initialization and basic operations on vectors (addition, scalar product,
etc.)
Matrices (Mat): initialization and basic operations on sparse or dense matrices
(factorizations, transposition, etc.)
Simplified linear equation solvers (SLES), an overlay of iterative methods
The compilation will be preprocessed to substitute the generic types of PETSc (Scalar,
Vec, Mat, ...) by the appropriate structures and descriptors.
#include "mat.h"
PetscInitialize(&argc,&argv,(char *)0,PETSC_NULL);
ierr = OptionsGetInt(PETSC_NULL,"-n",&n,&flg);
Creation of a general sparse matrix
ierr = MatCreate(PETSC_COMM_WORLD, n, n, &C);
ierr = OptionsHasName(PETSC_NULL,"-column_oriented",&flg);
if (flg) {ierr = MatSetOption(C,MAT_COLUMN_ORIENTED);
for ( i=0; i<6; i++ ) v[i] = (double) i;
midx[0] = 0; midx[1] = 2; midx[2] = 3;
nidx[0] = 1; nidx[1] = 3;
ierr = MatSetValues(C, 3, midx, 2, nidx, v, ADD_VALUES);
ierr = MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY);
ierr = MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY);
ierr = MatDestroy(C);
PetscFinalize();
return 0;
}
Chapter 5
Grid computing
5.1. Introduction
For several years, Distributed Computing and the associated technologies have been in a
constant technological and economic evolution. Technologies are becoming increasingly mature and
sophisticated. Computing and storage servers see their quality ratio
price constantly increasing by incorporating new technological and manufacturing innovations.
The same observation can be applied to network technologies and bandwidth.
offer that is becoming unlimited from an applicative point of view.
The response to these changes is to move to a distributed computing model allowing
to fully exploit the resources and capabilities offered. This environment will provide a service and
uniform and economically viable access to infrastructure resources.
This evolution is known as 'Grid Computing' or 'grid computing'.
The term 'The Grid' or 'computing grid' was first introduced in the United States.
during the 1990s to describe a distributed computing infrastructure used in projects of
scientific and industrial research.
In one of the earliest documents dealing with grid computing concepts, researchers attempt
to provide a detailed definition of the objectives, structure, and architecture of the computing grids.
Six fundamental questions are established that anyone involved in design must consider.
development or the use of calculation grids may arise:
Why do we need calculation grids?
What types of applications will benefit from computing grids?
Who will use the calculation grids?
How will the calculation grids be used?
What are the components involved in the design of calculation grids?
What are the obstacles to overcome for the calculation grids to become
omnipresent?
The grids are currently the subject of numerous projects, implemented by various
architectures. There is no single definition that is unanimously recognized.
It is important to know what advantages a calculation grid can offer that the
infrastructures and current technologies are not able to ensure. We then expose
some of the reasons that may lead to deploying a calculation grid.
Due to the fact that the resources federated by a computing grid are geographically dispersed
and available in significant quantities ensures the continuity of service if certain resources
become inaccessible. The grid control and management software will be able to
submit the calculation request to other resources.
A computing grid will be able to aggregate a significant amount of resources in order to provide the
computing power needed for many applications and that even supercomputers
more modern ones cannot provide.
Depending on the nature and extent of the grid, the aggregated resources may range from all the
workstations of a university to all the supercomputers of research organizations in a country.
As examples of applications, we can mention distributed simulation in the
meteorology, cosmology, and aeronautics...
The main challenge for designers of such grids is the dynamic and random nature of
requests made by users that can constitute a large population.
In such applications, a computing grid can absorb and store significant amounts.
generated information.
As an example of applications, we can mention the production of a map of
the universe, long-term weather forecasting, quantum simulations ...
A grid is a collection of resources that the user can benefit from. The resources
are generally divided into several types:
1. Processor cycles: there are several ways to exploit unused processor cycles of
machines participating in the grid. The first is to run an application on a machine
remote instead of the local processor. The second is to use an application designed to run its
different parts in parallel on different processors. The third is to run multiple
occurrences of the same application on different machines in order to process different data more
quickly.
2. Storage capacity: the second type of resources available in a grid is capacity
storage. Indeed, the machines participating in the grid will be able to provide a part of the capacity of
storage necessary for the functioning of the grid. The storage capacities in a grid may
to be used in order to increase the offered capacity, performance, sharing efficiency, and reliability.
3. Special equipment and high-license software: some software whose license prices
will be present in only a few copies in the grid. This grid will allow
so by exposing them to many users, a better use of these software. It is a matter of
even for certain special equipment such as electron microscopes and devices
medical ...
Although each project has its own architecture, a general architecture is important for
explain some fundamental concepts of grids.
machine with a resource description language (amount of memory required, CPU time, ...)
.) independent of the machine used.
There are many middleware or software components that can provide them.
features known as Unicore (German middleware), LEGION (American), JINI
our Middleware Sun, CORBA (one of the concepts of the OMG - Object Management Group), DCOM, SOAP or
.NET. But the one everyone is talking about today is Globus, the only complete, open middleware.
source and free.
The ideal grid environment will thus provide transparent access to resources by hiding all the
physical differences.
The fourth layer includes all the tools and paradigms that can assist developers.
to design and write applications that can run on the grid. It particularly includes
compilers, libraries, parallel application design tools as well as
programming interfaces or APIs (resource discovery and booking, security mechanisms,
storage ...) that application developers will be able to use.
The last layer groups the applications themselves, which are of a varied nature:
scientific, medical, financial, engineering projects ...
From a topological point of view, grids are of three types according to the increasing order of extent.
geographical and complexity: Intragrids, Extragrids and
Intergrilles (Intergrids).
The simplest of the grids is the intragrid, composed of a relatively simple set of
resources and services belonging to a single organization.
The main features of such a grid are the presence of an interconnection network.
high-performance and high-speed, in a unique security domain controlled by the administrators of
the organization and a relatively static and homogeneous set of resources. A company can
to be led to build an intragrid to increase the computing power of its teams
research and development while maintaining a low level of investment in terms of
new infrastructures (for example, AMD during the design phase of its processors
K6 and K7 [2]).
An intergrid consists of aggregating the grids of multiple organizations into a single grid.
the main features of such a grid are the presence of a very interconnected network
heterogeneous high and low bandwidth (LAN / WAN), from several distinct security domains and sometimes
different and even contradictory security policies, and a very dynamic set of
resources.
Intergrids will often be implemented during large industrial projects (design
of an aircraft by an aeronautics consortium for example) or scientific (protein modeling)
where several organizations will be invited to participate.
With the birth of the concept of computing grid, the concept of virtual organization
Organization) appears. Users will be able to be grouped according to their different interests, in
such organizations, each with their own policy. Each virtual organization will implement the
providing these users with a set of resources in the form of a grid.
It should be noted that the notion of intergrid is today tending to be confused with that of Global
Although grids offer several advantages, only certain types of applications will be able to benefit from them.
performing the calculations. And when the same data is used by multiple nodes it becomes
it is necessary to replicate this data in several places on the grid. Therefore, one must arrange for
each node accesses the closest data. This illustrates the importance of the presence of a
service for locating this data.
Some data is static in nature, while others are dynamic. In the latter case, and if these
data is replicated in several places on the grid, the designer will have to consider the issue of the
update of the various replicas and the overall consistency of the data.
For certain types of data, it will be urgent to propagate any changes as quickly as possible.
possible for all replies. Sometimes it is not urgent and thus helps to improve the
global performance of the application in terms of execution time. The update and access
Simultaneous data raise issues of consistency of this data. For this, mechanisms
Appropriate locking and synchronization mechanisms must be used. It then becomes necessary
to avoid, to prevent, and to detect all well-known issues of deadlock and starvation in
distributed computing.
Finally, we mention that a single application can have several instances that
are executed in parallel in different places of the grid in order to minimize the effects of failures
that may occur. These different instances will need to coordinate in order not to modify the data.
in an incoherent manner and leave them in an erroneous state.
Most current grid projects remain scientific projects. They are still the
needs for computing power or massive data processing that remain the motivations
first users. These arguments leave traditional companies completely indifferent.
Several projects for creating calculation grids are underway and are benefiting from the support of
universities, research centers, and industrialists.
a) Europe
a.1) Community projects
Following the work of the pioneers from the United States of America and Europe, platforms of
Software development for distributed computing such as Globus, Condor, Unicore are available.
Europe has managed to set up a functional testing framework in which 20 participate.
European centers, in the context of the EDG (European DataGrid) project.
The goal of the EGEE project (Enabling Grids for eScience in Europe) is to integrate the grids
national, regional and current thematic priorities to create a European framework for research
European. This infrastructure will be connected with other grids globally, including between
other than that of the US NSF (National Science Foundation), thus contributing to the emergence
from a planetary grid.
This infrastructure will be built by carrying out two pilot projects, one in particle physics.
in high energies and the other in biomedical.
The first project is the Large Hadron Collider Computing Grid (LHCG), for which a grid
is necessary to process the 12 to 14 petabytes of annual data resulting either from experiments or
CERN simulations. The analysis will require the equivalent of 70,000 of the fastest processors.
Today... Its results are of interest to about 6000 scientists from universities and laboratories.
whole world.
The other project is Biomedical Grids, for which several communities collaborate to process
data from bioinformatics and the healthcare system.
North America
TeraGRID: is the result of many years of effort to deploy the largest architecture
worldwide distributed for scientific research. TeraGrid is expected to represent a power of
calculation of 20 teraflops, with the ability to manage and store nearly a petabyte of data, and
a high-resolution visualization environment.
Access Grid: This grid was developed by the Argonne National Laboratory.
Earth System Grid II: It is created for the purpose of being able to carry out climate simulations.
Search for ExtraTerrestrial Intelligence (SETI@home): SETI@home is certainly
the most popular grid application. It concerns the search for extraterrestrial intelligence.
This project uses computers connected to the Internet to analyze data from
of a radio telescope.
[Link]: LeGrid MP Global @ [Link] has served, among other things, for the Research project for
the Cancer sponsored by Intel and the University of Oxford and that of Anthrax Research
sponsored by Intel and Microsoft
•Grid Physics Network, Particle Physics Daa Grid, NASA Information Power Grid, …
b.2) Canada
c) Asia
c.1) Japan
•Naregi: The Japanese government, commercial entities, and universities have unveiled the
Naregi project (National Research Grid Initiative) which aims to create a supercomputer at
starting from computers spread throughout the country. This meta-computer is expected to reach a capability of
100 Tflops in 2007.
BioGrid: It is a project involving Japan and China, between Osaka University and the Institute
of Microbiology of the Academy of Sciences of China.
c.2) China
•CNGrid (China National Grid Project): It is a key project of the National High-Tech program.
R&D (863 projects).
China Education and Research Grid: The project began in 2003 with six universities. Once
I finished, the grid will serve over 200,000 students and university members spread over about a
hundred of sites.
Australia
Nimrod: The initiator of these projects is Rajkumar Buyya, who completed a thesis to obtain a PhD.
whose dissertation title is: "Economic-based Distributed Resource Management and
Scheduling for Grid Computing in April 2002.
Some references
Table of contents
Course objectives
Prerequisites....................................................................................................................................................1
Course Summary....................................................................................................................................1
Chapter 1
Generalities on parallelism..................................................................................................................2
1.1. Motivation and definition of a distributed system
1.1.1. Motivation
1.1.2. Definition of a distributed system...........................................................................................3
1.2. What is parallelism? ......................................................................................................3
1.3. Definition of an algorithm.............................................................................................................4
1.4. Importance of parallelism............................................................................................................5
1.5. Parallel programming models.............................................................................................5
1.6. Key concepts of parallelism........................................................................................................9
1.6.1. User time (wallclock time) and computation time (cpu time) ......................................9
1.6.2. Load balancing .............................................................................10
1.6.3. At what level to parallelize?...................................................................................................10
1.7. The dangers of parallelization ..........................................................................................11
1.8. The top500
Chapter 2................................................................................................................................................13
Parallel programming models......................................................................................................13
2.1. Introduction
2.2. Models of parallel machines .................................................................................................13
2.2.1. Principles of parallel machines
2.2.2. Classification of parallel machines..................................................................................17
2.2.3. Fine-grained models ...............................................................................................................19
2.2.4. Coarse grain models.............................................................................................................23
2.3. Steps for parallelizing a task...........................................................................................23
2.3.1. Helping the compiler to parallelize.......................................................................................25
2.3.2. Distributing the data to be processed.................................................................................................26
2.3.3. Parallelizing your program with OpenMP...........................................................................28
2.3.4. Parallelizing your program with MPI ..................................................................................29
2.4. Cost of modeling ...................................................................................................................30
2.4.1. Calculation of parallel complexity..........................................................................................30
2.4.2. Amdahl's Law....................................................................................................................31
2.5. Summary of Parallelism Models...........................................................................................32
Chapter 3................................................................................................................................................34
Parallel programming with MPI.........................................................................................................34
3.1 Introduction
3.2. Some concepts
3.2.1. Message exchange............................................................................................................34
3.2.2. The Master and the Slaves
3.2.3. Synchronous or asynchronous messages, blocking or non-blocking ...................................35
3.2.5. Risk of deadlock ..............................................................................................36
3.3. Basic example
3.4. Sending messages between two threads (point-to-point communication).....................................37
3.4.1 Basic Syntax.....................................................................................................................38