Notes
Notes
• For example, distributed computing can encrypt large volumes of data; solve
physics and chemical equations with many variables; and render high-
quality, three-dimensional video animation. Distributed systems, distributed
programming, and distributed algorithms are some other terms that all refer
to distributed computing.
Distributed computing
Distributed computing
Characteristics of Distributed Computing.
o Decentralization: The system is spread across multiple nodes (computers), and no
single node has complete control over the entire system.
o Resource Sharing: Distributed computing enables multiple nodes to share resources
such as hardware, software, and data for collective processing.
o Scalability: It can scale horizontally by adding more nodes to handle increased
workloads.
o Fault Tolerance: The system is designed to continue functioning even when individual
components fail.
o Concurrency: Multiple computations or processes can run simultaneously across
different nodes to improve overall system efficiency.
o Transparency: Distributed systems abstract their complexity, providing users with a
unified view as if interacting with a single system.
Distributed computing
How does distributed computing work?
Distributed computing works by computers passing messages to each other within the
distributed systems architecture. Communication protocols or rules create a dependency
between the components of the distributed system. This interdependence is called coupling,
and there are two main types of coupling.
• Loose coupling: In loose coupling, components are weakly connected so that changes to
one component do not affect the other. For example, client and server computers can be
loosely coupled by time. Messages from the client are added to a server queue, and the client
can continue to perform other functions until the server responds to its message.
• Tight coupling: High-performing distributed systems often use tight coupling. Fast local
area networks typically connect several computers, which creates a cluster. In cluster
computing, each computer is set to perform the same task. Central control systems, called
clustering middleware, control and schedule the tasks and coordinate communication between
the different computers.
Distributed computing
Types of Distributed Computing architecture
In distributed computing, you design applications that can run on several computers instead of
on just one computer. You achieve this by designing the software so that different computers
perform different functions and communicate to develop the final solution. There are four main
types of distributed architecture
Client-server architecture: Client-server is the most common method of software
organization on a distributed system. The functions are separated into two categories: clients
and servers.
i. Clients: Clients have limited information and processing ability. Instead, they make requests
to the servers, which manage most of the data and other resources. You can make requests
to the client, and it communicates with the server on your behalf.
ii. Servers: Server computers synchronize and manage access to resources. They respond to
client requests with data or status information. Typically, one server can handle requests
from several machines
Distributed computing
Distributed computing
• Three-tier architecture: In three-tier distributed systems, client machines remain as the
first tier you access. Server machines, on the other hand, are further divided into two
categories:
Application servers
• Application servers act as the middle tier for communication. They contain the application
logic or the core functions that you design the distributed system for.
Database servers
• Database servers act as the third tier to store and manage the data. They are responsible
for data retrieval and data consistency.
• By dividing server responsibility, three-tier distributed systems reduce communication
bottlenecks and improve distributed computing performance.
Distributed computing
N-tier architecture: N-tier models include several different client-server systems
communicating with each other to solve the same problem. Most modern distributed systems
use an n-tier architecture with different enterprise applications working together as one system
behind the scenes.
Distributed computing
Peer-to-peer architecture: Peer-to-peer distributed systems assign equal responsibilities to
all networked computers. There is no separation between client and server computers, and any
computer can perform all responsibilities. Peer-to-peer architecture has become popular for
content sharing, file streaming, and blockchain networks.
Distributed computing
• Advantages of distributed computing?
o Scalability: Distributed systems can grow with your workload and requirements. You
can add new nodes, that is, more computing devices, to the distributed computing
network when they are needed.
o Availability: Your distributed computing system will not crash if one of the computers
goes down. The design show’s fault tolerance because it can continue to operate even if
individual computers fail.
o Consistency: Computers in a distributed system share information and duplicate data
between them, but the system automatically manages data consistency across all the
different computers. Thus, you get the benefit of fault tolerance without compromising
data consistency.
o Transparency: Distributed computing systems provide logical separation between the
user and the physical devices. You can interact with the system as if it is a single
computer without worrying about the setup and configuration of individual machines.
You can have different hardware, middleware, software, and operating systems that
work together to make your system function smoothly.
Distributed computing
• Disadvantages of Distributed Computing:
o Complexity: Designing and managing distributed systems is complex due to the need
for communication between nodes, fault tolerance, and consistency mechanisms.
o Security: With multiple computers in the network, security vulnerabilities increase as
more endpoints need protection.
o Network Dependence: Distributed systems rely heavily on a stable and efficient
network. Network latency or failures can disrupt performance.
o Debugging Challenges: Troubleshooting and debugging distributed systems can be
difficult, as issues often arise from interactions between different nodes.
o Cost: Initial setup, hardware, and maintenance costs can be higher than centralized
systems.
o Data Synchronization Issues: Maintaining consistency across distributed nodes can
be challenging, especially when dealing with large-scale, real-time data updates.
Grid Computing
Grid computing is a computing infrastructure that combines computer resources spread over
different geographical locations to achieve a common goal. All unused resources on multiple
computers are pooled together and made available for a single task. Organizations use grid
computing to perform large tasks or solve complex problems that are difficult to do on a single
computer.
For example, meteorologists use grid computing for weather modelling. Weather modelling is a
computation-intensive problem that requires complex data management and analysis.
Processing massive amounts of weather data on a single computer is slow and time consuming.
That’s why meteorologists run the analysis over geographically dispersed grid computing
infrastructure and combine the results.
Grid Computing
Importance of grid computing
Organizations use grid computing for several reasons.
a) Efficiency: With grid computing, you can break down an enormous, complex task into
multiple subtasks. Multiple computers can work on the subtasks concurrently, making grid
computing an efficient computational solution.
b) Cost: Grid computing works with existing hardware, which means you can reuse existing
computers. You can save costs while accessing your excess computational resources. You
can also cost-effectively access resources from the cloud.
c) Flexibility: Grid computing is not constrained to a specific building or location. You can set
up a grid computing network that spans several regions. This allows researchers in different
countries to work collaboratively with the same supercomputing power.
Grid Computing
Use cases of grid computing
The following are some common applications of grid computing.
o Financial services: Financial institutions use grid computing primarily to solve problems
involving risk management. By harnessing the combined computing powers in the grid, they
can shorten the duration of forecasting portfolio changes in volatile markets.
o Gaming: The gaming industry uses grid computing to provide additional computational
resources for game developers. The grid computing system splits large tasks, such as
creating in-game designs, and allocates them to multiple machines. This results in a faster
turnaround for the game developers.
o Entertainment: Some movies have complex special effects that require a powerful
computer to create. The special effects designers use grid computing to speed up the
production timeline. They have grid-supported software that shares computational resources
to render the special-effect graphics.
o Engineering: Engineers use grid computing to perform simulations, create models, and
analyze designs.
Grid Computing
Components in grid computing
In grid computing, a network of computers works together to perform the same task. The
following are the components of a grid computing network.
Nodes: The computers or servers on a grid computing network are called nodes. Each node
offers unused computing resources such as CPU, memory, and storage to the grid network. At
the same time, you can also use the nodes to perform other unrelated tasks. There is no limit
to the number of nodes in grid computing. There are three main types of nodes: control,
provider, and user nodes.
Grid middleware: Grid middleware is a specialized software application that connects
computing resources in grid operations with high-level applications. For example, it handles
your request for additional processing power from the grid computing system.
• It controls the user sharing of available resources to prevent overwhelming the grid
computers. The grid middleware also provides security to prevent misuse of resources in grid
computing.
Grid Computing
Grid computing architecture
Grid architecture represents the internal structure of grid computers. The following layers are
broadly present in a grid node:
• 1. The top layer consists of high-level applications, such as an application to perform
predictive modeling.
• 2. The second layer, also known as middleware, manages and allocates resources
requested by applications.
• 3. The third layer consists of available computer resources such as CPU, memory, and
storage.
• 4. The bottom layer allows the computer to connect to a grid computing network.
Grid Computing
How does grid computing work?
Grid nodes and middleware work together to perform the grid computing task. In grid operations, the
three main types of grid nodes perform three different roles.
o User node: A user node is a computer that requests resources shared by other computers in grid
computing. When the user node requires additional resources, the request goes through the
middleware and is delivered to other nodes on the grid computing system.
o Provider node: In grid computing, nodes can often switch between the role of user and provider. A
provider node is a computer that shares its resources for grid computing. When provider machines
receive resource requests, they perform subtasks for the user nodes, such as forecasting stock prices
for different markets. At the end of the process, the middleware collects and compiles all the results to
obtain a global forecast.
o Control node: A control node administers the network and manages the allocation of the grid
computing resources. The middleware runs on the control node. When the user node requests a
resource, the middleware checks for available resources and assigns the task to a specific provider
node.
Grid Computing
Grid Computing
Types of grid computing?
Grid computing is generally classified as follows.
a) Computational grid: A computational grid consists of high-performance computers. It allows
researchers to use the combined computing power of the computers. Researchers use computational
grid computing to perform resource-intensive tasks, such as mathematical simulations.
b) Scavenging grid: While similar to computational grids, CPU scavenging grids have many regular
computers. The term scavenging describes the process of searching for available computing resources
in a network of regular computers. While other network users access the computers for non-
grid–related tasks, the grid software uses these nodes when they are free. The scavenging grid is also
known as CPU scavenging or cycle scavenging.
c) Data grid: A data grid is a grid computing network that connects to multiple computers to provide
large data storage capacity. You can access the stored data as if on your local machine without having
to worry about the physical location of your data on the grid.
Cluster Computing
Cluster computing is a type of computing where multiple computers are connected so they work
together as a single system. The term “cluster” refers to the network of linked computer
systems programmed to perform the same task.
• Computing clusters typically consist of servers, workstations and personal computers (PCs) that
communicate over a local area network (LAN) or a wide area network (WAN).
• Cluster computing is a kind of distributed computing, a type of computing that links computers
together on a network to perform a computational task, increase computational power and function as
a single computer. Each computer, or “node,” in a computer network has an operating system (OS) and
a central processing unit (CPU) core that handles the tasks required for the software to run properly.
• Because of its high performance and high availability, cluster computing has many applications,
including cloud computing, artificial intelligence (AI), scientific research and big data analytics.
Cluster Computing
How does cluster computing work?
At its most fundamental level, cluster computing uses a LAN to connect multiple, independent
computers in a network. In the architecture of the cluster, each computer on the network is
referred to as a “node” and is controlled by middleware, software that enables communication
between each machine. Users of the cluster can use each computer’s resources as though they
were a single machine, rather than individual machines connected via a LAN.
A computing cluster can connect as few as two nodes or as many as thousands. For example,
a Beowulf cluster typically uses commercial grade PCs connected via a LAN and can be a
relatively affordable alternative to a supercomputer for certain tasks.
Kubernetes, on the other hand—a container-related, cluster-adjacent technology that’s
essential to cloud computing—supports clusters of up to 5,000 separates but connected nodes.
Kubernetes is used in many kinds of cloud deployments, including hybrid
cloud and multicloud architectures, as well as DevOps and application modernization
Cluster Computing
Cluster computing architecture
Cluster computing architectures consist of a group of interconnected, individual computers
working together as a single machine. Each computing resource is linked via a high-speed
connection, such as a LAN, and referred to in the architecture of the system as a single node.
Each node has an OS, memory and input and output (I/O) functions.
There are two types of cluster architectures, open or closed. In an open cluster, each computer
has its own IP address. In a closed cluster, each node is hidden behind a gateway node.
Because the gateway node controls access to the other nodes and IP addresses can be found
on the internet, closed clusters are less of a security risk than open clusters.
Cluster Computing
Benefits of Computing Clusters
There are several benefits to using clusters for computing tasks. They offer:
o Increased Processing Power: By distributing tasks across multiple nodes, clusters can
handle larger workloads and process data more quickly than a single computer.
o Improved Data Integrity: With redundancies built into the system, data loss or
corruption is less likely, ensuring the integrity of your data.
o Enhanced Reliability: Clusters can continue to function even if a node fails, providing
uninterrupted service.
o Scalability: Clusters can be easily expanded by adding more nodes, allowing for increased
capacity when needed.
Cluster Computing
Applications of Computing Clusters
Computing Clusters are used across a wide variety of fields and applications, including:
o Scientific Research: Clusters can handle the processing of complex calculations and
simulations.
o 3D Rendering: The parallel processing power of clusters can dramatically reduce the time
it takes to render high-quality 3D images.
o Big Data Analytics: Clusters can quickly process large volumes of data and provide
insights in real-time.
o AI and Machine Learning: Clusters are highly effective for tasks in artificial
intelligence and machine learning. They can efficiently process and analyze vast datasets,
which is essential for training complex AI models and algorithms.
Cloud Computing
Cloud computing is the delivery of computing services—including servers, storage, databases,
networking, software, analytics, and intelligence—over the internet (“the cloud”) to offer faster
innovation, flexible resources, and economies of scale.
Cloud computing is a big shift from the traditional way businesses think about IT resources.
• Cost: Moving to the cloud helps companies optimize IT costs. This is because cloud computing
eliminates the capital expense of buying hardware and software and setting up and running onsite
datacenters—the racks of servers, the round-the-clock electricity for power and cooling, and the IT
experts for managing the infrastructure. It adds up fast.
• Speed: Most cloud computing services are provided self service and on demand, so even vast
amounts of computing resources can be provisioned in minutes, typically with just a few mouse clicks,
giving businesses a lot of flexibility and taking the pressure off capacity planning.
Cloud Computing
• Global scale: The benefits of cloud computing services include the ability to scale elastically. In cloud
speak, that means delivering the right amount of IT resources—for example, more or less computing
power, storage, bandwidth—right when they’re needed, and from the right geographic location.
• Productivity: Onsite datacenters typically require a lot of “racking and stacking”—hardware setup,
software patching, and other time-consuming IT management chores. Cloud computing removes the
need for many of these tasks, so IT teams can spend time on achieving more important business goals.
• Performance: The biggest cloud computing services run on a worldwide network of secure
datacenters, which are regularly upgraded to the latest generation of fast and efficient computing
hardware. This offers several benefits over a single corporate datacenter, including reduced network
latency for applications and greater economies of scale.
• Reliability: Cloud computing makes data backup, disaster recovery, and business continuity easier
and less expensive because data can be mirrored at multiple redundant sites on the cloud provider’s
network.
• Security: Many cloud providers offer a broad set of policies, technologies, and controls
that strengthen your security posture overall, helping protect your data, apps, and infrastructure from
potential threats.
Cloud Computing
How cloud computing works ?
Cloud computing service models are based on the concept of sharing on-demand computing
resources, software, and information over the internet. Companies or individuals pay to access
a virtual pool of shared resources, including compute, storage, and networking services, which
are located on remote servers that are owned and managed by service providers.
One of the many advantages of cloud computing is that you only pay for what you use. This
allows organizations to scale faster and more efficiently without the burden of having to buy
and maintain their own physical data centers and servers.
In simpler terms, cloud computing uses a network (most often, the internet) to connect users to a cloud
platform where they request and access rented computing services. A central server handles all the
communication between client devices and servers to facilitate the exchange of data. Security and privacy
features are common components to keep this information secure and safe.
When adopting cloud computing architecture, there is no one-size-fits-all. What works for another
company may not suit you and your business needs. In fact, this flexibility and versatility is one of the
hallmarks of cloud, allowing enterprises to quickly adapt to changing markets or metrics.
Cloud Computing
Cloud Computing
Types of cloud computing deployment models
a) Public cloud: are run by third-party cloud service providers. They offer compute, storage,
and network resources over the internet, enabling companies to access shared on-demand
resources based on their unique requirements and business goals.
b) Private cloud: are built, managed, and owned by a single organization and privately
hosted in their own data centers, commonly known as “on-premises” or “on-prem.” They
provide greater control, security, and management of data while still enabling internal users
to benefit from a shared pool of compute, storage, and network resources.
c) Hybrid cloud: combine public and private cloud models, allowing companies to leverage
public cloud services and maintain the security and compliance capabilities commonly found
in private cloud architectures.
Cloud Computing
What are the types of cloud computing services?
There are three main types of cloud computing service models that you can select based on the level of
control, flexibility, and management your business needs:
a) Infrastructure as a service (IaaS): Infrastructure as a service (IaaS) offers on-demand access to
IT infrastructure services, including compute, storage, networking, and virtualization. It provides the
highest level of control over your IT resources and most closely resembles traditional on-premises IT
resources.
b) Platform as a service (PaaS): Platform as a service (PaaS) offers all the hardware and software
resources needed for cloud application development. With PaaS, companies can focus fully on
application development without the burden of managing and maintaining the underlying
infrastructure.
c) Software as a service (SaaS): Software as a service (SaaS) delivers a full application stack as a
service, from underlying infrastructure to maintenance and updates to the app software itself. A SaaS
solution is often an end-user application, where both the service and the infrastructure are managed
and maintained by the cloud service provider.
Cloud Computing
Use cases of Cloud Computing
Cloud computing offers a broad range of possible applications that can benefit organizations.
Here are some common use cases:
o Infrastructure scaling: Many organizations, including those in retail, have wildly varying
needs for compute capacity. Cloud computing easily accommodates these fluctuations.
o Disaster recovery: Rather than building more data centers to ensure continuity during
disasters, businesses use cloud computing to safely back up their digital assets.
o Data storage: Cloud computing helps overloaded data centers by storing large volumes of
data, making it more accessible, easing analysis, and making backup easier.
o Application development: Cloud computing offers enterprise developers quick access to
tools and platforms for building and testing applications, speeding up time to market.
o Big data analytics: Cloud computing offers almost unlimited resources to process large
volumes of data to speed research and reduce time to insights.
PVM (Parallel Virtual Machine)
PVM (Parallel Virtual Machine)
• PVM (Parallel Virtual Machine) is a software system that enables a collection of
heterogeneous computers to be used as a coherent and flexible concurrent computational
resource. The individual computers may be shared- or local-memory multiprocessors, vector
supercomputers, specialized graphics engines, or scalar workstations, that may be
interconnected by a variety of networks, such as ethernet, FDDI, etc. PVM support software
executes on each machine in a user-configurable pool, and presents a unified, general, and
powerful computational environment of concurrent applications. User programs written in C
or Fortran are provided access to PVM through the use of calls to PVM library routines for
functions such as process initiation, message transmission and reception, and
synchronization via barriers or rendezvous. Users may optionally control the execution
location of specific application components. The PVM system transparently handles message
routing, data conversion for incompatible architectures, and other tasks that are necessary
for operation in a heterogeneous, network environment.
PVM (Parallel Virtual Machine)
• PVM is particularly effective for heterogeneous applications that exploit specific strengths of
individual machines on a network. As a loosely coupled concurrent supercomputer
environment, PVM is a viable scientific computing platform. The PVM system has been used
for applications such as molecular dynamics simulations, superconductivity studies,
distributed fractal computations, matrix algorithms, and in the classroom as the basis for
teaching concurrent computing.
• The PVM software provides a unified framework within which parallel programs can be
developed in an efficient and straightforward manner using existing hardware PVM enables
a collection of heterogeneous computer systems to be viewed as a single parallel virtual
machine PVM transparently handles all message routing data conversion and task
scheduling across a network of incompatible computer architectures.
PVM (Parallel Virtual Machine)
How PVM Works ?
How PVM Works ?
• Parallel Virtual Machine (PVM) is a software framework that transforms a network of
interconnected computers into a single, unified parallel-processing system. It operates using
a master-slave model, where the master task oversees the computation and manages
the distribution of work among slave tasks. The computers participating in this virtual
machine, collectively called the host pool, can be heterogeneous, meaning they may differ
in their operating systems, architectures, or computational capacities. Each task, whether
master or slave, is assigned a unique Task ID (TID), which facilitates communication and
coordination between them.
• At the core of PVM's functionality is its efficient message-passing system, which allows
tasks to exchange data and control signals seamlessly. The master task spawns slave tasks
on available hosts using the pvm_spawn() function. It assigns specific parts of the problem
to each slave and communicates with them by packaging data using functions like
pvm_pkint() and sending it via pvm_send(). The slave tasks receive these messages using
pvm_recv() and unpack them with corresponding functions like pvm_upkint(). After
processing the assigned work, slaves send the results back to the master, which aggregates
them to produce the final output.
How PVM Works ?
The PVM daemon (pvmd) is a crucial component of the system, running on each host in the
pool to manage task scheduling, communication, and resource allocation. Developers interact
with the PVM framework using a comprehensive library of functions that simplify writing and
executing distributed applications. The system is flexible and scalable, allowing developers to
add or remove nodes dynamically, making it well-suited for heterogeneous and evolving
environments.
For example, in a distributed computation of Pi, the master task divides the workload into
segments and assigns each segment to a slave task. The slaves independently calculate their
assigned portions and return the results to the master, which aggregates them into an
approximation of Pi. This approach demonstrates PVM's capability to harness the collective
computational power of multiple machines for efficient problem-solving. Its simplicity, coupled
with its ability to support heterogeneous systems, makes PVM a valuable tool for parallel and
distributed computing.
PVM (Parallel Virtual Machine)
Summary:
PVM operates on a master-slave model:
1. Host Pool: A group of computers, possibly of different architectures, is connected in a
network.
2. Task Execution: Tasks are programs running on these hosts, with one acting as the
master and the others as slaves.
3. Communication: Tasks communicate via message-passing, using PVM’s built-in libraries.
4. Coordination: The master task assigns work to slave tasks and collects results.
Tutorial on how to install and start PVM
The Parallel Virtual Machine (PVM) software is freely available and can be obtained through the
Netlib distribution service, which provides a wide range of software tools for scientific computing.
Here's a step-by-step guide to install and Start PVM:
1st Step : Downloading PVM which there are different options to obtain it , as mentioned below :
Using FTP:
o Connect to the Netlib FTP server at [Link].
o Navigate to the pvm directory.
o Download the files listed in the directory. The index file provides a description of the available
files.
Using the Web:
o Access the PVM files via a web browser at the URL: [Link]
Tutorial on how to install and start PVM
Using Email:
o Send an email to netlib@[Link] with the message send index from pvm.
o An automated system will respond with a list of files and further instructions on
obtaining the software.
Using Xnetlib (Graphical Interface):
o Xnetlib is an X-Window-based interface for browsing and downloading Netlib software.
o To obtain Xnetlib, send an email to netlib@[Link] with the message send [Link]
from xnetlib, or download it via FTP from [Link]/pub/xnetlib.
o files via a web browser at the URL: [Link]
Tutorial on how to install and start PVM
2nd Step : Installation of PVM
Once you have obtained the PVM software (usually as a uuencoded, compressed tar file),
follow these steps to install it:
Unpack the Distribution:
o Decode the file using uudecode.
o Uncompress, it using gunzip.
o Extract the contents using tar xvf <filename>.
o This creates a directory named pvm at the location of extraction.
Tutorial on how to install and start PVM
Set Environment Variables:
o Set the PVM_ROOT variable to the location of the pvm directory.
Example for csh:
setenv PVM_ROOT ~/pvm
o Set the PVM_ARCH variable to specify the system architecture.
You can use the [Link] file in the PVM_ROOT/lib directory for automatic detection.
Add the following to your .cshrc file:
source $PVM_ROOT/lib/[Link]
Tutorial on how to install and start PVM
Build PVM for Your System:
o Navigate to the PVM_ROOT directory and run make.
o This command compiles the software for the current architecture and creates the
required executables and libraries.
Configure Remote Hosts:
o Add the hostnames of machines you want to use in a .rhosts file on each machine. This
enables remote execution.
Tutorial on how to install and start PVM
Starting and Using PVM
Start PVM:
o Run the pvm command from any machine where PVM is installed.
o This opens the PVM console.
Configure Hosts:
o Add a host to the virtual machine: pvm add hostname
o Remove a host from the virtual machine: pvm delete hostname
o View the virtual machine configuration: pvm conf
o List running tasks: pvm ps
Tutorial on how to install and start PVM
Stop PVM:
o Quit the console while keeping the virtual machine running:
• quit
o Halt the virtual machine and stop all tasks:
• pvm halt
If available, use the XPVM graphical interface for easier management of PVM virtual machines.
XPVM provides real-time visualizations of task execution, message passing, and system load,
enhancing the user experience. Start XPVM with the xpvm command and manage hosts via its
menu interface.
Hello Program Example
Master Program (master.c):
• #include <stdio.h>
• #include "pvm3.h"
• int main() {
• pvm_initsend(PvmDataDefault);
• pvm_pkstr("Hello, Slave!");
• pvm_send(tid, 1);
• char message[100];
• pvm_recv(-1, 2);
• pvm_upkstr(message);
• return 0;
• }
Hello Program Example
Slave Program (slave.c):
• #include <stdio.h>
• #include "pvm3.h"
• int main() {
• char message[100];
• pvm_recv(-1, 1);
• pvm_upkstr(message);
• pvm_initsend(PvmDataDefault);
• pvm_pkstr("Hello, Master!");
• pvm_send(pvm_parent(), 2);
• return 0;
• }
Calculating Pi Example
Master Program (master.c):
• #include <stdio.h>
• #include "pvm3.h"
• #define NUM_SLAVES 2
• int main() {
• pvm_initsend(PvmDataDefault);
• pvm_send(tids[i], 1);
• }
Calculating Pi Example
Master Program (master.c):
• for (int i = 0; i < NUM_SLAVES; i++) {
• pvm_recv(-1, 2);
• pvm_upkdouble(&partial_result, 1, 1);
• result += partial_result;
• }
• pvm_exit();
• return 0;
• }
Calculating Pi Example
Slave Program (slave.c):
• #include <stdio.h>
• #include "pvm3.h"
• }
• }
Calculating Pi Example
Slave Program (slave.c):
• int main() {
• double result;
• pvm_recv(-1, 1);
• pvm_upkint(&segment, 1, 1);
• pvm_upkint(&total_segments, 1, 1);
• pvm_initsend(PvmDataDefault);
• pvm_pkdouble(&result, 1, 1);
• pvm_send(pvm_parent(), 2);
• pvm_exit();
• return 0;}
MPI Programming (hello world and calculating PI)
Hello World Program (hello_mpi.c)
• #include <mpi.h>
• #include <stdio.h>
• int main(int argc, char** argv) {
• MPI_Init(&argc, &argv);
• int world_rank;
• MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
• int world_size;
• MPI_Comm_size(MPI_COMM_WORLD, &world_size);
• printf("Hello World from rank %d out of %d processors\n", world_rank, world_size);
• MPI_Finalize();
• return 0;}
MPI Programming (hello world and calculating PI)
Compile the program:
• mpicc hello_mpi.c -o hello_mpi
Run the program using mpirun:
• mpirun -np 10 -hostfile hosts ./hello_mpi
MPI Programming (hello world and calculating PI)
Pi Calculation Program (calculate_pi_mpi.c)
• #include <mpi.h>
• #include <stdio.h>
• MPI_Init(&argc, &argv);
• MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
• MPI_Comm_size(MPI_COMM_WORLD, &world_size);
• h = 1.0 / num_intervals;
• x = h * (i - 0.5);
#include<studio.h>
Thread 1 Thread 2 Thread 3
#include<cuda.h> (x=0, y=0) (x=1, y=0) (x=2, y=0)
Global void add(int *d, int *e, int *f){ Thread41 Thread 5 Thread 6
(x=0, y=1) (x=1, y=1) (x=2, y=1)
int x=threadIdx.x; MATRIX B
MATRIX A
int y=threadIdx.y; 1 2 3 2 2 7
int id=blockDim.x*y+x; 4 5 6 8 5 2
f[id]=d[id] + e[id];
INDEX 0 1 2 3 4 5
} 1 2 3 4 5 6
VALUE
0 1 2 3 4 5
2 2 7 8 5 2
MATRIX ADDITION PROGRAM…
Int main () {
Int a[2][3] = {{1,2,3},{4,5,6}}, b[2][3]={{2,2,7},{8,5,2}},
c[2][3], *d, *e, *f;
cudaMalloc((void**))&d, 6*sizeof(int));
cudaMalloc((void**))&e, 6*sizeof(int));
cudaMalloc((void**))&f, 6*sizeof(int));
cudaMemcpy (d, &a,6*sizeof(int),cudaMemcpyHostToDevice);
cudaMemcpy (e, &b,6*sizeof(int),cudaMemcpyHostToDevice);
Dim3 threadblock(3,2) //(c,r)
add<<<1,threadblock>>>(d,e,f);
cudaMemcpy(&c,f,6*sizeof(int),cudaMemcpyDeviceToHost);
MATRIX ADDITION PROGRAM…
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
printf(“%d\t”, c[i][j]);
printf(“\n”);
cudaFree(d);
cudaFree(e);
cudaFree(f);
cudaDeviceSychronize();
return 0;
}
CUDA MEMORY MODEL
• The CUDA memory model is a model that gives programmers
explicit control over the memory hierarchy, including how to
allocate, deallocate, and move data between the host and device.
• The CUDA memory model unifies the separate host and device
memory systems, and exposes the full memory hierarchy.
CUDA MEMORY MODEL DIAGRAM
MEMORY ALLOCATION IN CUDA DEVICE
• We simply use the following codes in memory allocation
cudaMalloc()
• Allocates object in the device global memory
• Requires two parameters
• Address of a pointer to the allocated object
• Size of allocated object
cudaFree()
• Frees objects from device global memory
• Pointer to freed object
CUDA MEMORY RULES
• Currently can only transfer data from host to global (and constant
memory) and not host directly to shared.
• Constant memory used for data that does not change (i.e.
readonly by GPU)
• Shared memory is said to provide up to 15x speed of global
memory
• Registers have similar speed to shared memory if reading same
address or no bank conflicts.
CUDA MATRIX TRANSPOSE PROGRAM
• #include <stdio.h>
• #include <cuda_runtime.h>
• // Matrix dimensions
• #define N 4 // Rows
• #define M 4 // Columns
• // CUDA kernel for matrix transpose
• __global__ void matrixTranspose (int *input, int *output, int rows, int
cols) {
• // Calculate row and column index of the element
• int row = blockIdx.y * blockDim.y + threadIdx.y;
• int col = blockIdx.x * blockDim.x + threadIdx.x;
• if (row < rows && col < cols) {
• // Transpose element (row, col) -> (col, row)
• output[col * rows + row] = input[row * cols + col];
• }
• }
CUDA MATRIX TRANSPOSE PROGRAM…
• int main() {
• // Host matrices
• int h_input[N * M], h_output[N * M];
• // Initialize input matrix
• printf("Input Matrix:\n");
• for (int i = 0; i < N; ++i) {
• for (int j = 0; j < M; ++j) {
• h_input[i * M + j] = i * M + j + 1; // Sequential values
• printf("%d ", h_input[i * M + j]);
• }
• printf("\n");
• }
CUDA MATRIX TRANSPOSE PROGRAM…
• // Device matrices
• int *d_input, *d_output;
• size_t size = N * M * sizeof(int);
• // Allocate memory on the device
• cudaMalloc((void **)&d_input, size);
• cudaMalloc((void **)&d_output, size);
• // Copy input matrix from host to device
• cudaMemcpy(d_input, h_input, size,
cudaMemcpyHostToDevice);
• // Define thread block and grid dimensions
• dim3 threadsPerBlock(16, 16);
• dim3 blocksPerGrid((M + threadsPerBlock.x - 1) /
threadsPerBlock.x,
• (N + threadsPerBlock.y - 1) / threadsPerBlock.y);
CUDA MATRIX TRANSPOSE PROGRAM…
• // Launch kernel
• matrixTranspose<<<blocksPerGrid, threadsPerBlock>>>(d_input, d_output,
N, M);
• // Copy result back to host
• cudaMemcpy(h_output, d_output, size, cudaMemcpyDeviceToHost);
• // Print transposed matrix
• printf("\nTransposed Matrix:\n");
• for (int i = 0; i < M; ++i) {
• for (int j = 0; j < N; ++j) {
• printf("%d ", h_output[i * N + j]);
• }
• printf("\n");
• }
• // Free device memory
• cudaFree(d_input);
• cudaFree(d_output);
• return 0;
• }
DIAGRAM PRESENTATION OF THE PROGRAM
DIAGRAM PRESENTATION OF THE PROGRAM…
PROGRAM TO CALCULATE “PI” IN CUDA WITH 2^16
NUMBER OF INTERVALS
• Let’s understand our problem
PROGRAM TO CALCULATE “PI” IN CUDA WITH 2^16
NUMBER OF INTERVALS…
• Here we are dividing the are into smaller discrete areas so that
we can sum them at the end to get the total area.
PROGRAM TO CALCULATE “PI” IN CUDA WITH 2^16
NUMBER OF INTERVALS…
• #include <stdio.h>
• #include <cuda.h>
• #define NUM_INTERVALS (1 << 16) // 2^16 = 65536 intervals
• // CUDA Kernel to calculate partial sum
• __global__ void compute_pi(double *d_partial_sum, int
num_intervals) {
• int idx = threadIdx.x + blockIdx.x * blockDim.x;
• int total_threads = blockDim.x * gridDim.x;
• double step = 1.0 / (double)num_intervals;
• double sum = 0.0;
• for (int i = idx; i < num_intervals; i += total_threads) {
• double x = (i + 0.5) * step;
• sum += 4.0 / (1.0 + x * x);
• }
• d_partial_sum[idx] = sum * step;
• }
PROGRAM TO CALCULATE “PI” IN CUDA WITH 2^16
NUMBER OF INTERVALS…