SlideShare a Scribd company logo
© 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

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

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

P threads
P threadsP threads
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
Mahmoud Ouf
 
Threads
ThreadsThreads
Threads
Sameer Shaik
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
Janu Jahnavi
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
Janu 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.0
Richard Banks
 
Pthread
PthreadPthread
Coding for multiple cores
Coding for multiple coresCoding for multiple cores
Coding for multiple cores
Lee Hanxue
 
Cuda 2011
Cuda 2011Cuda 2011
Cuda 2011
coolmirza143
 
Chap7 slides
Chap7 slidesChap7 slides
Chap7 slides
BaliThorat1
 
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
Tim 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 Cluster
André Rømcke
 
Project Jugaad
Project JugaadProject Jugaad
Parallel program design
Parallel program designParallel program design
Parallel program design
ZongYing Lyu
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Ganesh Samarthyam
 
Processes
ProcessesProcesses
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
Amazon Web Services
 
Why rust?
Why rust?Why rust?
Why rust?
Mats Kindahl
 
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
Enrico Zimuel
 
Understanding Threads in operating system
Understanding Threads in operating systemUnderstanding Threads in operating system
Understanding Threads in operating system
Harrytoye2
 

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

Linux Internals Part - 2
Linux Internals Part - 2Linux Internals Part - 2
Linux Internals Part - 2
SysPlay eLearning Academy for You
 
Linux Internals Part - 1
Linux Internals Part - 1Linux Internals Part - 1
Linux Internals Part - 1
SysPlay eLearning Academy for You
 
Cache Management
Cache ManagementCache Management
Introduction to BeagleBone Black
Introduction to BeagleBone BlackIntroduction to BeagleBone Black
Introduction to BeagleBone Black
SysPlay eLearning Academy for You
 
Introduction to BeagleBoard-xM
Introduction to BeagleBoard-xMIntroduction to BeagleBoard-xM
Introduction to BeagleBoard-xM
SysPlay eLearning Academy for You
 
Platform Drivers
Platform DriversPlatform Drivers
BeagleBone Black Bootloaders
BeagleBone Black BootloadersBeagleBone Black Bootloaders
BeagleBone Black Bootloaders
SysPlay eLearning Academy for You
 
BeagleBone Black Booting Process
BeagleBone Black Booting ProcessBeagleBone Black Booting Process
BeagleBone Black Booting Process
SysPlay eLearning Academy for You
 
BeagleBoard-xM Bootloaders
BeagleBoard-xM BootloadersBeagleBoard-xM Bootloaders
BeagleBoard-xM Bootloaders
SysPlay eLearning Academy for You
 
BeagleBoard-xM Booting Process
BeagleBoard-xM Booting ProcessBeagleBoard-xM Booting Process
BeagleBoard-xM Booting Process
SysPlay eLearning Academy for You
 
Serial Drivers
Serial DriversSerial Drivers
SPI Drivers
SPI DriversSPI Drivers
Linux System
Linux SystemLinux 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

A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 

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?