0% found this document useful (0 votes)
2 views12 pages

Multithreaded Programming

The document provides an overview of multithreaded programming, explaining the concept of threads as lightweight processes that share resources within a larger process. It discusses the differences between processes and threads, advantages of using threads, the lifecycle of a thread, and various multithreading models. Additionally, it addresses threading issues such as race conditions, synchronization, and deadlocks.

Uploaded by

Ishtiaq Malik
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

Multithreaded Programming

The document provides an overview of multithreaded programming, explaining the concept of threads as lightweight processes that share resources within a larger process. It discusses the differences between processes and threads, advantages of using threads, the lifecycle of a thread, and various multithreading models. Additionally, it addresses threading issues such as race conditions, synchronization, and deadlocks.

Uploaded by

Ishtiaq Malik
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Multithreaded Programming

Introduction to Multithreaded Programming


What is a Thread?

A thread is the smallest unit of CPU execution within a process. A process may contain one or
more threads. Each thread performs a separate task while sharing the same memory space and
resources of the process.

A thread is often called a lightweight process because it requires fewer resources than a
complete process.

Example

Consider a web browser:

• One thread handles the user interface.


• One thread downloads web pages.
• One thread plays videos.
• One thread manages network communication.

All these threads run within the same browser process and work simultaneously.

Process vs Thread
Process

A process is an independent program in execution.

Examples:

• MS Word
• Google Chrome
• VLC Media Player

Each process has:

• Separate memory space


• Separate resources
• Separate address space

Thread
A thread is a part of a process.

Threads share:

• Code section
• Data section
• Files
• Memory

But each thread has its own:

• Program Counter (PC)


• Registers
• Stack

Difference Between Processes and Threads


Feature Process Thread
Memory Separate memory Shared memory

Resource Sharing Difficult Easy


Creation Time Slow Fast

Context Switching Expensive Less expensive


Communication IPC required Direct sharing

Execution Unit Heavyweight Lightweight

Advantages of Threads Over Processes


1. Improved Responsiveness
Applications remain responsive even when one thread is busy.

Example:

While downloading a file, the user can still interact with the browser.

Benefit

Better user experience.


2. Resource Sharing
Threads share process resources automatically.

Shared resources include:

• Memory
• Open files
• Variables

This makes communication easier.

3. Faster Creation
Creating a thread requires fewer system resources than creating a process.

Reason

No need to allocate separate memory space.

4. Faster Context Switching


Switching between threads is faster because threads share the same address space.

Result

Improved performance.

5. Better CPU Utilization


Multiple threads can execute simultaneously on multi-core processors.

Example:

A 4-core CPU can execute 4 threads at the same time.

6. Parallelism
Threads allow true parallel execution.

Example

Image editing software:


• One thread applies filters.
• Another thread loads images.
• Another thread saves files.

Components of a Thread
Each thread contains:

1. Thread ID

Unique identification number.

2. Program Counter (PC)

Keeps track of the next instruction.

3. Register Set

Stores temporary data during execution.

4. Stack

Contains:

• Function calls
• Local variables
• Return addresses

Thread Lifecycle
A thread passes through several states during execution.

1. New State
Thread is created but not yet started.

Example:

Thread t = new Thread();


The thread exists but does not execute.

2. Ready State
Thread is prepared to run and waiting for CPU allocation.

Characteristics:

• Ready for execution


• Waiting in ready queue

3. Running State
CPU assigns processor time.

Thread executes instructions.

Activities

• Calculations
• File operations
• User requests

4. Blocked / Waiting State


Thread waits for an event.

Examples:

• User input
• File read operation
• Network response

The thread temporarily stops execution.

5. Terminated State
Thread finishes execution.

Reasons:

• Task completed
• Error occurred
• Explicit termination
Thread Lifecycle Diagram
New
|
V
Ready
|
V
Running
/ \
/ \
Waiting Ready
\ /
\ /
Running
|
V
Terminated

Multithreading
Definition
Multithreading is the ability of a process to execute multiple threads concurrently.

Purpose

To perform multiple tasks simultaneously.

Example

Online Banking Application:

Thread 1

Balance checking

Thread 2

Money transfer

Thread 3

Notification sending

Thread 4
Transaction history retrieval

All operate together.

Multithreading Models
A multithreading model defines how user threads are mapped to kernel threads.

1. Many-to-One Model
In this model:

Multiple user-level threads are mapped to a single kernel thread.

Diagram
User Threads
T1
T2
T3
T4
|
V
Single Kernel Thread

Working

• Many user threads exist.


• Operating system sees only one kernel thread.
• Thread management occurs in user space.

Example Systems
• Early Java Green Threads
• GNU Portable Threads

2. One-to-One Model
Each user thread corresponds to one kernel thread.

Diagram
T1 ---> K1
T2 ---> K2
T3 ---> K3
T4 ---> K4

Working

Every user thread has a separate kernel thread.

The operating system schedules them independently.

Examples

• Windows
• Linux
• Modern Java Threads

3. Many-to-Many Model
Multiple user threads are mapped to multiple kernel threads.

Diagram
User Threads
T1
T2
T3
T4
T5
T6

|
V

Kernel Threads
K1
K2
K3

Working

Several user threads share several kernel threads.

The operating system schedules kernel threads efficiently.

Example

Some UNIX-based systems support this model.


Comparison of Thread Models
Feature Many-to-One One-to-One Many-to-Many

Parallel Execution No Yes Yes


Blocking Effect All Threads Single Thread Limited

Performance Fast Moderate High


Complexity Low Medium High

Resource Usage Low High Moderate

Threading Issues
When multiple threads access shared resources, several problems may occur.

1. Race Condition
Definition
A race condition occurs when multiple threads access and modify shared data
simultaneously, causing unpredictable results.

Example
Suppose:

Bank Balance = 1000

Two threads perform:

Thread A withdraws 100


Thread B withdraws 200

Expected Balance:

700

But due to simultaneous execution:

900
or
800
may occur.

This incorrect result is called a race condition.

Why Race Conditions Occur


Because:

• Threads execute concurrently.


• Operations are interrupted.
• Shared variables are not protected.

2. Synchronization
Definition
Synchronization is a technique used to control thread access to shared resources.

It prevents race conditions.

Objective
Ensure that only one thread enters the critical section at a time.

Synchronization Mechanisms
1. Mutex (Mutual Exclusion)

A lock allowing only one thread to access shared data.

Thread A acquires lock


Thread B waits
Thread A releases lock
Thread B executes

2. Semaphore

A signaling mechanism controlling access to resources.

Binary Semaphore

Values:

0 or 1
Acts like a mutex.

Counting Semaphore

Allows multiple threads simultaneously.

Example:

Printer pool with 5 printers.

Semaphore value:

Only five threads can use printers.

3. Monitor

High-level synchronization structure.

Provides:

• Mutual exclusion
• Condition variables

Used in Java synchronization.

3. Deadlock
Definition
A deadlock occurs when two or more threads wait indefinitely for resources held
by each other.

As a result:

No thread can proceed.

Example
Thread A

Holds Resource 1

Waiting for Resource 2


Thread B

Holds Resource 2

Waiting for Resource 1

Thread A --> Resource 1


|
Waiting for Resource 2

Thread B --> Resource 2


|
Waiting for Resource 1

Neither thread can continue.

System becomes stuck.

You might also like