0% found this document useful (0 votes)
10 views20 pages

Threads

Uploaded by

Imy
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)
10 views20 pages

Threads

Uploaded by

Imy
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
You are on page 1/ 20

Threads

Dr. Abdeldjalil Labed

Dr. Abdeldjalil Labed Threads 1 / 20


Motivation

A process is a cool abstraction to run a new program


However, . . .
Its expensive to create a new process
space : PCB, page tables, queues etc.
time : creating OS structures, fork and copy addr space, etc.
Processes do not share resources well :
A single process cannot benefit from multi-cores CPU
Context switching between processes is expensive
There is a high communication overheads between processes
How can we increase concurrency within a process cheaply ?

Dr. Abdeldjalil Labed Threads 2 / 20


What is a thread?

A thread is a lightweight process


A sequence of instructions that can be scheduled to run
independently by the operating system in a program.
A basic unit of CPU utilization (scheduling).
Example : Imagine a program that contains a number of
procedures. Now imagine all of these procedures are scheduled by
the operating system to run simultaneously and/or independently
from the main function. That would describe a "multi-threaded"
program.

Dr. Abdeldjalil Labed Threads 3 / 20


Multithreading
A single-threaded process : is heavyweight process with one
thread, which means it can perform only one task at a time within
its own address space.
Multithreaded process : a process made up of a number of
different concurrent threads

Dr. Abdeldjalil Labed Threads 4 / 20


Examples
Web browsers : Modern web browsers use multithreading to handle
multiple tasks simultaneously, such as loading multiple tabs or web
pages, running JavaScript code, rendering images, and playing media.
This allows for a smoother user experience.
Word processors : Multithreading in word processors enables users to
perform tasks like spell-checking, grammar-checking, and auto-saving
without interrupting the user’s typing experience.
Web servers : Web servers use multithreading to handle multiple client
requests concurrently, allowing them to serve web pages and resources to
multiple users simultaneously.

Dr. Abdeldjalil Labed Threads 5 / 20


Multithreading
Each thread has its own :
Thread id, stack, set of registers including PC and SP.
Each thread shares the following with peer threads :
address space, code section, data section, heap, OS resources
(open files)...etc.

Dr. Abdeldjalil Labed Threads 6 / 20


Processes vs Threads
Processes are containers in which threads execute concurrently
The OS provides protection and isolation among processes.
Keeps buggy program from trashing the system

No protection and no isolation between threads :


they can access each other’s data directly.
Sharing data among threads is cheap ;
Threads ensure concurrency and address space ensure protection.
Dr. Abdeldjalil Labed Threads 7 / 20
Benefits of multithreading
Economy
Creating concurrency does not require creating new processes
“faster / better / cheaper”
thread switching has lower overhead than context switching
Responsiveness
may allow continued execution if part of process is blocked.
Resource sharing
threads share resources of process, all see the same address
space
Scalability
Allows building parallel programs
Allows one process to take advantage of multi-core
architectures

Dr. Abdeldjalil Labed Threads 8 / 20


Threads Interfaces

POSIX threads, often referred to as Pthreads :


A POSIX standardized (specified by IEEE) thread API for
thread creation and synchronization
it specifies the behavior of the thread library
Implementation is up to development of the library
Common in Unix-like operating systems : Linux, Mac OS X,
Solaris.. etc.
Microsoft Windows has its own Thread API
Win32/Win64 threads

Dr. Abdeldjalil Labed Threads 9 / 20


Thread management

main section
pthread_create() (create thread)
pthread_join() : wait for thread to
finish (optional : used if you want to
wait for the thread termination)
thread section
begins at function pointer
runs until pthread_exit()

Dr. Abdeldjalil Labed Threads 10 / 20


Creating a thread
To use pthreads, we need to include pthread.h and specify an
object of type pthread_t that indicates the thread ID.
The pthread_create function starts a new thread in the calling
process.
Where :
thread is a pointer to a variable that will
hold the id of the newly created thread.
attr is a set of attributes and features to
apply to the thread
start_routine is a pointer to a function that
we want to run
arg is a pointer that will be passed to our
function
void *(*start_routine) (void *) is difficult to read ! It means a pointer that
takes a void * pointer and returns a void * pointer.

Dr. Abdeldjalil Labed Threads 11 / 20


Waiting for a thread

A parent thread is made to wait for a child thread.


The pthread_join function waits for the thread to terminate by
collecting its exit status.

Where,
thread is a variable that will hold the id of the thread.
retval is a double pointer (a pointer to a void pointer) that will be used to
store the exit status of the joined thread.

Dr. Abdeldjalil Labed Threads 12 / 20


Setup
Open Bash terminal (Git Bash on Windows / Terminal on Mac)
Then open a Ubuntu container using the following command :

# On Windows :
winpty docker run -it --name Threads techtn/ubuntu :p2 bash
# On Mac or Linux :
docker run -it --name Threads techtn/ubuntu :p2 bash
If the container exits, use the following commands to re-run it and
retrieve your previous work :
# On Windows :
winpty docker attach Threads
# On Mac or Linux :
docker attach Threads

Dr. Abdeldjalil Labed Threads 13 / 20


Example 1

The option -pthread tells the gcc compiler that your program requires
threading support.
Dr. Abdeldjalil Labed Threads 14 / 20
Exiting a thread
The pthread_exit function terminates the calling thread and
returns a value
This function is usually written at the end of the starting routine.
If a value is returned by a thread upon ending, its reference is
passed as an argument.
Since a thread’s local variables (stack) are destroyed when it exits,
only references to global (data section) or dynamically allocated
variables (heap) are returned.

Where,
retval is a pointer to a return value

Dr. Abdeldjalil Labed Threads 15 / 20


Example2

Dr. Abdeldjalil Labed Threads 16 / 20


Example3

Note : If you want to pass more than one variable to the starting
routine use STRUCT
Dr. Abdeldjalil Labed Threads 17 / 20
Thread Issues
Consider the following function :

Now suppose thread “A” executes the following

... at the same time thread B” executes

What is the final value of accounts[1] ?


Dr. Abdeldjalil Labed Threads 18 / 20
Thread issues: Race condition

Race conditions : A race condition occurs when there is an


uncoordinated concurrent access to shared resources (e.g. memory
or device registers), which leads to incorrect behaviour of the
program, deadlocks or lost work.
In the next session we will see how to handle this using
synchronization via MUTEXes (mutual exclusion) and
semaphores.

Dr. Abdeldjalil Labed Threads 19 / 20


Example 4

Dr. Abdeldjalil Labed Threads 20 / 20

You might also like