SlideShare a Scribd company logo
1 of 21
© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
POSIX Threads
2© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
What to Expect?
W’s of Threads
Single & Multi-threaded Processes
Advantages of using threads
Creating & Passing data to threads
Thread Attributes
Thread Cancellation
Thread Specific data
3© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
W’s of Threads
Need for the multitasking within the program
Event driven programming
Thread exists within a process
Each thread may be executing a different part of
the program at any given time
Linux Kernel schedules them asynchronously
4© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Multi-Process vs Multi-Threaded
code
data
files
regs
stack
...
Parent
Process
...code data files
regs
stack
...
Child
Process
Child
Process
code
data
files
regs
stack
...
code
data
files
regs
stack
...
Main
Process
regs
stack
...
Thread
regs
stack
...
Thread
5© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Threads vs Multiple Processes
Threads Advantages
Inexpensive Creation & Termination
Inexpensive Context Switching
Communication is Inherent & Far More
As already sharing almost all resources
No kernel interaction involved
Threads Disadvantages
Security because of inherent sharing
6© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
W's of pthread
POSIX standard (IEEE Std 1003.1) thread APIs
Defined as “pthread” library with a set of
C language programming types
C language function calls
Prototyped in pthread.h header/include file
Library may or may not be part of standard C library
On Linux
pthread library is not part of libc (libc.so, libc.a)
Provided separately as: libpthread.so, libpthread*.a
Compiling: gcc -o <out_file> <input_file> -lpthread
7© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Thread Creation
int pthread_create(
pthread_t *thread_id, → Id of the thread created
const pthread_attr_t *attr, → Thread interaction attributes
void *(*start_routine)(void *), → Function to start execution
void *arg → Argument to pass any data to thread
); → 0 on success; error code < 0 on error
attr = NULL implies default thread attributes
Thread exits on return by the *start_routine
arg could be used to create different threads with same start function
Function returns immediately scheduling both the threads
asynchronously
8© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Thread Termination
Thread terminates
Normally
On start_routine termination
By call to pthread_exit(void *exit_val);
Abnormally
On cancellation
Return value / status is a void *
Return value from start_routine
Or, exit_val
Or, PTHREAD_CANCELED
9© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Waiting for my threads
Parent could wait for its threads using
int pthread_join(pthread_t tid, void **retval);
tid → Id of thread to wait for
*retval → Thread exit status, if retval != NULL
Returns
0 on success
error code < 0 on error
Try out: thread_join.c, thread_return.c
Observe: thread_unsafe.c
10© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Not waiting for my threads
What if the main thread doesn't join?
A clean up of the thread is not guaranteed
If main thread quits, process quits
All threads in it cease to exist & are cleaned
If main thread runs, and don't want to join
Creating detached threads is the option
By modifying the thread attributes
Detached threads can't be joined
And they clean up on their termination
11© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Thread Attributes
Provides a mechanism for fine-tuning the behaviour
of individual threads
Configurable by passing a valid “attr” to
pthread_create
Before that, pthread_attr_t object needs
Initialization: int pthread_attr_init(pthread_attr_t *attr);
Modification using various pthread_attr_set* functions
And after that, pthread_attr_t object needs
Destruction: int pthread_attr_destroy(pthread_attr_t *attr);
Have a look @ thread_attr.c
12© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Let's Detach Threads
Attribute Modification Function
int pthread_attr_setdetachstate(
pthread_attr_t *attr,
int detachstate
);
detachstate
PTHREAD_CREATE_DETACHED
PTHREAD_CREATE_JOINABLE
Try out: thread_detach.c
13© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Some Thread Id Functions
pthread_t pthread_self();
Returns the id of the current thread
Can be used for thread specific variations / data
int pthread_equal(pthread_t t1, pthread_t t2)
Compares thread ids t1 & t2
Returns non-zero on equal, zero otherwise
pthread_join(pthread_self(), NULL); ???
Returns EDEADLK
14© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Thread Cancellation
Terminating other thread
int pthread_cancel(pthread_t tid);
When & Where the cancelled thread exits?
Depends on its cancel state & type attribute
These attributes could be set using
int pthread_setcancelstate(int state, int *oldstate);
int pthread_setcanceltype(int type, int *oldtype);
States
PTHREAD_CANCEL_DISABLE, PTHREAD_CANCEL_ENABLE
Type
PTHREAD_CANCEL_DEFERRED, PTHREAD_CANCEL_ASYNCHRONOUS
Try out: thread_cancel.c
15© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Thread Cancellation ...
Why Uncancellable?
To enable critical section implementations
What are Cancellable Points?
Calls to certain functions specified by POSIX.1
standards. Refer “man 7 pthreads” for list
Deferred Cancellation still doesn't solve
Resource Leak during Cancellation
Only solution: Cleanup Handler
16© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Cleanup Handler Specifics
Function which gets called when a thread exits
either
Due to cancellation
Call to pthread_exit
But not by return of the thread start function
Should be called explicitly
Typical tasks are cleanups of
Thread-specific data keys
Memory allocations
Mutex waits
17© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Cleanup Handler ...
Registration
int pthread_cleanup_push(
void (*handler)(void *), → cleanup handler
void *arg → argument to the cleanup handler
);
Unregistration
int pthread_cleanup_pop(
int execute → also execute the handler, if non-zero
);
These two calls must be balanced
Experiment: thread_cancel_cleanup.c
18© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Thread-Specific Data
By default all data is shared (public)
Good for inter thread communication
But no privacy for a thread
Though in some cases it may be desirable
An Example
Multiple threads to log in their respective files
Individual thread needs to store & retrieve
Its own log file pointer
And so pthreads do support it
19© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Thread-Specific Data ...
Implemented using a thread specific data area
In the same Process Address Space
Variables in this area are duplicated for each thread
But should be accessed with special atomic functions for setting
and retrieving values
APIs needed
int pthread_key_create(pthread_key_t *k, void (*dest)(void *));
int pthread_key_delete(pthread_key_t key);
int pthread_setspecific(pthread_key_t key, void *val);
void *pthread_getspecific(pthread_key_t key);
Let's see the thread_logging.c example
20© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
What all have we learnt?
W’s of Threads
Single & Multi-threaded Processes
Advantages of using threads
Creating & Passing data to threads
Thread attributes
Thread Cancellation
Thread Specific data
21© 2019 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Any Queries?

More Related Content

What's hot (20)

Linux Internals Part - 3
Linux Internals Part - 3Linux Internals Part - 3
Linux Internals Part - 3
 
Kernel Debugging & Profiling
Kernel Debugging & ProfilingKernel Debugging & Profiling
Kernel Debugging & Profiling
 
Kernel Debugging & Profiling
Kernel Debugging & ProfilingKernel Debugging & Profiling
Kernel Debugging & Profiling
 
Block Drivers
Block DriversBlock Drivers
Block Drivers
 
Toolchain
ToolchainToolchain
Toolchain
 
Understanding the BBB
Understanding the BBBUnderstanding the BBB
Understanding the BBB
 
Interrupts
InterruptsInterrupts
Interrupts
 
Synchronization
SynchronizationSynchronization
Synchronization
 
Processes
ProcessesProcesses
Processes
 
Architecture Porting
Architecture PortingArchitecture Porting
Architecture Porting
 
Linux Kernel Overview
Linux Kernel OverviewLinux Kernel Overview
Linux Kernel Overview
 
Embedded Software Design
Embedded Software DesignEmbedded Software Design
Embedded Software Design
 
Video Drivers
Video DriversVideo Drivers
Video Drivers
 
Introduction to Linux
Introduction to LinuxIntroduction to Linux
Introduction to Linux
 
Linux User Space Debugging & Profiling
Linux User Space Debugging & ProfilingLinux User Space Debugging & Profiling
Linux User Space Debugging & Profiling
 
Real Time Systems
Real Time SystemsReal Time Systems
Real Time Systems
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
I2C Drivers
I2C DriversI2C Drivers
I2C Drivers
 
Bootloaders
BootloadersBootloaders
Bootloaders
 
BeagleBone Black Bootloaders
BeagleBone Black BootloadersBeagleBone Black Bootloaders
BeagleBone Black Bootloaders
 

Similar to POSIX Threads

Python multithreading
Python multithreadingPython multithreading
Python multithreadingJanu Jahnavi
 
Python multithreading
Python multithreadingPython multithreading
Python multithreadingJanu Jahnavi
 
Improving app performance using .Net Core 3.0
Improving app performance using .Net Core 3.0Improving app performance using .Net Core 3.0
Improving app performance using .Net Core 3.0Richard Banks
 
Coding for multiple cores
Coding for multiple coresCoding for multiple cores
Coding for multiple coresLee Hanxue
 
Five cool ways the JVM can run Apache Spark faster
Five cool ways the JVM can run Apache Spark fasterFive cool ways the JVM can run Apache Spark faster
Five cool ways the JVM can run Apache Spark fasterTim Ellison
 
SfDay 2019: Head first into Symfony Cache, Redis & Redis Cluster
SfDay 2019: Head first into Symfony Cache, Redis & Redis ClusterSfDay 2019: Head first into Symfony Cache, Redis & Redis Cluster
SfDay 2019: Head first into Symfony Cache, Redis & Redis ClusterAndré Rømcke
 
Parallel program design
Parallel program designParallel program design
Parallel program designZongYing Lyu
 
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28Amazon Web Services
 
A quick start on Zend Framework 2
A quick start on Zend Framework 2A quick start on Zend Framework 2
A quick start on Zend Framework 2Enrico Zimuel
 
Understanding Threads in operating system
Understanding Threads in operating systemUnderstanding Threads in operating system
Understanding Threads in operating systemHarrytoye2
 

Similar to POSIX Threads (20)

P threads
P threadsP threads
P threads
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
Threads
ThreadsThreads
Threads
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
 
Improving app performance using .Net Core 3.0
Improving app performance using .Net Core 3.0Improving app performance using .Net Core 3.0
Improving app performance using .Net Core 3.0
 
Pthread
PthreadPthread
Pthread
 
Coding for multiple cores
Coding for multiple coresCoding for multiple cores
Coding for multiple cores
 
Cuda 2011
Cuda 2011Cuda 2011
Cuda 2011
 
Chap7 slides
Chap7 slidesChap7 slides
Chap7 slides
 
Five cool ways the JVM can run Apache Spark faster
Five cool ways the JVM can run Apache Spark fasterFive cool ways the JVM can run Apache Spark faster
Five cool ways the JVM can run Apache Spark faster
 
SfDay 2019: Head first into Symfony Cache, Redis & Redis Cluster
SfDay 2019: Head first into Symfony Cache, Redis & Redis ClusterSfDay 2019: Head first into Symfony Cache, Redis & Redis Cluster
SfDay 2019: Head first into Symfony Cache, Redis & Redis Cluster
 
Project Jugaad
Project JugaadProject Jugaad
Project Jugaad
 
Parallel program design
Parallel program designParallel program design
Parallel program design
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Processes
ProcessesProcesses
Processes
 
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
 
Why rust?
Why rust?Why rust?
Why rust?
 
A quick start on Zend Framework 2
A quick start on Zend Framework 2A quick start on Zend Framework 2
A quick start on Zend Framework 2
 
Understanding Threads in operating system
Understanding Threads in operating systemUnderstanding Threads in operating system
Understanding Threads in operating system
 

More from SysPlay eLearning Academy for You (13)

Linux Internals Part - 2
Linux Internals Part - 2Linux Internals Part - 2
Linux Internals Part - 2
 
Linux Internals Part - 1
Linux Internals Part - 1Linux Internals Part - 1
Linux Internals Part - 1
 
Cache Management
Cache ManagementCache Management
Cache Management
 
Introduction to BeagleBone Black
Introduction to BeagleBone BlackIntroduction to BeagleBone Black
Introduction to BeagleBone Black
 
Introduction to BeagleBoard-xM
Introduction to BeagleBoard-xMIntroduction to BeagleBoard-xM
Introduction to BeagleBoard-xM
 
Platform Drivers
Platform DriversPlatform Drivers
Platform Drivers
 
BeagleBone Black Bootloaders
BeagleBone Black BootloadersBeagleBone Black Bootloaders
BeagleBone Black Bootloaders
 
BeagleBone Black Booting Process
BeagleBone Black Booting ProcessBeagleBone Black Booting Process
BeagleBone Black Booting Process
 
BeagleBoard-xM Bootloaders
BeagleBoard-xM BootloadersBeagleBoard-xM Bootloaders
BeagleBoard-xM Bootloaders
 
BeagleBoard-xM Booting Process
BeagleBoard-xM Booting ProcessBeagleBoard-xM Booting Process
BeagleBoard-xM Booting Process
 
Serial Drivers
Serial DriversSerial Drivers
Serial Drivers
 
SPI Drivers
SPI DriversSPI Drivers
SPI Drivers
 
Linux System
Linux SystemLinux System
Linux System
 

Recently uploaded

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

POSIX Threads

  • 1. © 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. POSIX Threads
  • 2. 2© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. What to Expect? W’s of Threads Single & Multi-threaded Processes Advantages of using threads Creating & Passing data to threads Thread Attributes Thread Cancellation Thread Specific data
  • 3. 3© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. W’s of Threads Need for the multitasking within the program Event driven programming Thread exists within a process Each thread may be executing a different part of the program at any given time Linux Kernel schedules them asynchronously
  • 4. 4© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Multi-Process vs Multi-Threaded code data files regs stack ... Parent Process ...code data files regs stack ... Child Process Child Process code data files regs stack ... code data files regs stack ... Main Process regs stack ... Thread regs stack ... Thread
  • 5. 5© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Threads vs Multiple Processes Threads Advantages Inexpensive Creation & Termination Inexpensive Context Switching Communication is Inherent & Far More As already sharing almost all resources No kernel interaction involved Threads Disadvantages Security because of inherent sharing
  • 6. 6© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. W's of pthread POSIX standard (IEEE Std 1003.1) thread APIs Defined as “pthread” library with a set of C language programming types C language function calls Prototyped in pthread.h header/include file Library may or may not be part of standard C library On Linux pthread library is not part of libc (libc.so, libc.a) Provided separately as: libpthread.so, libpthread*.a Compiling: gcc -o <out_file> <input_file> -lpthread
  • 7. 7© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread Creation int pthread_create( pthread_t *thread_id, → Id of the thread created const pthread_attr_t *attr, → Thread interaction attributes void *(*start_routine)(void *), → Function to start execution void *arg → Argument to pass any data to thread ); → 0 on success; error code < 0 on error attr = NULL implies default thread attributes Thread exits on return by the *start_routine arg could be used to create different threads with same start function Function returns immediately scheduling both the threads asynchronously
  • 8. 8© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread Termination Thread terminates Normally On start_routine termination By call to pthread_exit(void *exit_val); Abnormally On cancellation Return value / status is a void * Return value from start_routine Or, exit_val Or, PTHREAD_CANCELED
  • 9. 9© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Waiting for my threads Parent could wait for its threads using int pthread_join(pthread_t tid, void **retval); tid → Id of thread to wait for *retval → Thread exit status, if retval != NULL Returns 0 on success error code < 0 on error Try out: thread_join.c, thread_return.c Observe: thread_unsafe.c
  • 10. 10© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Not waiting for my threads What if the main thread doesn't join? A clean up of the thread is not guaranteed If main thread quits, process quits All threads in it cease to exist & are cleaned If main thread runs, and don't want to join Creating detached threads is the option By modifying the thread attributes Detached threads can't be joined And they clean up on their termination
  • 11. 11© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread Attributes Provides a mechanism for fine-tuning the behaviour of individual threads Configurable by passing a valid “attr” to pthread_create Before that, pthread_attr_t object needs Initialization: int pthread_attr_init(pthread_attr_t *attr); Modification using various pthread_attr_set* functions And after that, pthread_attr_t object needs Destruction: int pthread_attr_destroy(pthread_attr_t *attr); Have a look @ thread_attr.c
  • 12. 12© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Let's Detach Threads Attribute Modification Function int pthread_attr_setdetachstate( pthread_attr_t *attr, int detachstate ); detachstate PTHREAD_CREATE_DETACHED PTHREAD_CREATE_JOINABLE Try out: thread_detach.c
  • 13. 13© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Some Thread Id Functions pthread_t pthread_self(); Returns the id of the current thread Can be used for thread specific variations / data int pthread_equal(pthread_t t1, pthread_t t2) Compares thread ids t1 & t2 Returns non-zero on equal, zero otherwise pthread_join(pthread_self(), NULL); ??? Returns EDEADLK
  • 14. 14© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread Cancellation Terminating other thread int pthread_cancel(pthread_t tid); When & Where the cancelled thread exits? Depends on its cancel state & type attribute These attributes could be set using int pthread_setcancelstate(int state, int *oldstate); int pthread_setcanceltype(int type, int *oldtype); States PTHREAD_CANCEL_DISABLE, PTHREAD_CANCEL_ENABLE Type PTHREAD_CANCEL_DEFERRED, PTHREAD_CANCEL_ASYNCHRONOUS Try out: thread_cancel.c
  • 15. 15© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread Cancellation ... Why Uncancellable? To enable critical section implementations What are Cancellable Points? Calls to certain functions specified by POSIX.1 standards. Refer “man 7 pthreads” for list Deferred Cancellation still doesn't solve Resource Leak during Cancellation Only solution: Cleanup Handler
  • 16. 16© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Cleanup Handler Specifics Function which gets called when a thread exits either Due to cancellation Call to pthread_exit But not by return of the thread start function Should be called explicitly Typical tasks are cleanups of Thread-specific data keys Memory allocations Mutex waits
  • 17. 17© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Cleanup Handler ... Registration int pthread_cleanup_push( void (*handler)(void *), → cleanup handler void *arg → argument to the cleanup handler ); Unregistration int pthread_cleanup_pop( int execute → also execute the handler, if non-zero ); These two calls must be balanced Experiment: thread_cancel_cleanup.c
  • 18. 18© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread-Specific Data By default all data is shared (public) Good for inter thread communication But no privacy for a thread Though in some cases it may be desirable An Example Multiple threads to log in their respective files Individual thread needs to store & retrieve Its own log file pointer And so pthreads do support it
  • 19. 19© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread-Specific Data ... Implemented using a thread specific data area In the same Process Address Space Variables in this area are duplicated for each thread But should be accessed with special atomic functions for setting and retrieving values APIs needed int pthread_key_create(pthread_key_t *k, void (*dest)(void *)); int pthread_key_delete(pthread_key_t key); int pthread_setspecific(pthread_key_t key, void *val); void *pthread_getspecific(pthread_key_t key); Let's see the thread_logging.c example
  • 20. 20© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. What all have we learnt? W’s of Threads Single & Multi-threaded Processes Advantages of using threads Creating & Passing data to threads Thread attributes Thread Cancellation Thread Specific data
  • 21. 21© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Any Queries?