SlideShare una empresa de Scribd logo
1 de 39
© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Threads
2© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
What to Expect?
Threads Overview
W's & How's of Threads
Comparison with Processes
Models for Threaded Programs
Possible Thread Implementations
Threads Programming in Linux: NPTL
3© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Recall
Why we needed a Process?
To execute multiple tasks at a time
What else did we get?
Process Creation (Copy) Overhead
Context Switch Baggage
IPC Overheads vs Synchronization Issues
Could we do any better?
What if we share as much as we can?
Reducing Copies, Switches, Communication Overheads
That's were the idea of threads popped-up
4© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
So, let's recall a Process
What all did it entail?
Address Space (Code, Variables, Stack, Heap)
Processor State (PC, Registers, …)
OS resources in use
File descriptors, IPC, Signal states & actions, Shared libraries, ...
Scheduling Info, Priority, ...
Preemption Info, Process State, …
Extras like
Process Info: pid, pgid, userid, gid, ...
Environment: Working directory, ...
What all & How can these be shared?
5© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
How's of Threads
Exist within the Process to use its resources
Yet be scheduled by the Kernel
And run as independent entities
By duplicating only the bare essentials
Stack & Stack pointer
PC & Other Registers
Scheduling Properties
Policy, Priority, Process / Execution States
Set of pending and blocked signals
Thread specific Data
6© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
How threads evolved?
Result of the dawn of event-driven programs
Where flow of control depends on the user input
Example: A modern GUI
Multiple Windows – Multiple I/Os
Multiple Asynchronous Events (menu pull down)
Anytime Actions (without blocking)
But all with the same Program / Process
7© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
8© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
Thread Blocking may lead to Process Blocking
On a single-threaded Kernel
Security because of inherent sharing
9© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Similarities with a Process
Scheduled like a Process & Share CPU
Only one thread active at a time
Execute sequentially on a uni-processor
Individual Thread Execution State
Independent Stack & Execution Sequence
Can create children
If one thread is blocked, another can run
10© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Differences from a Process
Threads in a Process are not totally
independent of one another
Have their own registers and stack but in the
same address space
Also, share global variables, file descriptors,
signal handlers, ...
Threads are designed to assist one other
Processes may or may not assist one another
As they may originate from different users
11© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Process vs Thread
Process Addr Space
func1() { … }
func2() { … }
......
main() { ... }
g_array
g_val
text
data
heap
Files
Locks
Sockets
Process ID
Group ID
User ID
main() var2
var1
stack Stack Pointer
Program Counter
Registers
Process
Multi-threaded
Process
func2() var4
var2
thread1
stack
Stack Pointer
Program Counter
Registers
func1() var5
var6
var3
Stack Pointer
Program Counter
Registers
thread2
stack
12© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
W's of Threads
Same code but different code execution
Same process but different process states
Same address space but different stack
Shared Variables (Data & Heap), Shared
File Descriptors, ...
Enabling trivial Communication & hence
needing Synchronization
13© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
When to use Threading?
Tasks with anyone of these criteria
Block for potentially long waits, say on I/O
Use many CPU cycles, i.e. CPU intensive
Must respond to asynchronous events
Of indeterminate frequency & duration
Are of lesser or greater importance than others
Are able to be performed in parallel with others
To achieve optimum performance on SMP architectures
14© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Design for Threading
Organize the program into discrete, independent
tasks which can execute concurrently
Example: If routine1 and routine2 can be
interchanged, overlapped and/or interleaved in real
time, they are candidates for threading
routine1
routine2
final
routine
routine2
routine1
final
routine
routine2
routine1
final
routine
routine2
routine1
final
routine
routine2
routine1
routine2
15© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Models for Threaded Programs
Delegation or Manager-Worker
Used when tasks could be interleaved
Example: Web server accepting & serving requests
Two varieties
Static worker pool
Dynamic worker pool
Pipeline
Used when tasks could be overlapped
Example: GUI application serving various events
Peer
Used when tasks could be concurrent
Example: Individual I/O Processing Threads
Producer-Consumer
Used when tasks are producers & consumers
Example: Manufacturing unit simulation
16© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Thread Safeness
Ability of an application to execute multiple
threads simultaneously
Without "clobbering" shared data
Without creating "race" conditions
Examples of thread unsafe applications
Two threads calling the same function (with side
effects), without synchronizing
Multiple threads accessing global variables without
access protection
Application using non-thread-safe libraries or library
functions
17© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Thread Implementations
Kernel-level Threads
Kernel knows & manages threads
Maintains global thread tables
Operated using system calls
User-level Threads
Threads implemented in user libraries
Operated using library functions
Kernel manages them as individual processes
18© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
“Kernel vs User” level Threads
Kernel-level Threads User-level Threads
Need modification to Kernel Kernel independent
Need a full TCB to manage & schedule Simple representation of TCB in User
Process Address Space
Thread Switching & Synchronization
needs Kernel Intervention
Thread Switching & Synchronization are
mere function calls
Slow & Inefficient Fast & Efficient
Good for applications that block
frequently
Needs non-blocking system calls (i.e.
multi-threaded kernel) to avoid entire
process blocking on a thread blocking
Processes with more threads may be
given more time
Processes get the same time slice
irrespective of the number of threads in it
LinuxThreads, NPTL GNU Portable Threads (Pth)
19© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Threads Support in Linux
Started with no real support except system call clone()
New process shares the address space with the parent
Used by LinuxThreads to provide 1x1 kernel-level threads library
Threads as child processes with different pid, sharing parent's address space
ps would show all threads as processes
Basically a new (child) process with Copy-On-Write bit turned off
Had issues with signal handling
Replaced by the NPTL using the same system call clone()
With same pid but different second level ids (thread ids) to achieve 1x1
Real “threads in a process”, starting execution from a specified procedure
ps would show only one process & threads under it
And equally well, using the efficient lwp mechanisms similar to thread libraries
Thus, NPTL is kernel-level thread library with close to user-level library efficiency
Try “ps m” & clone.c
20© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Native POSIX Thread Library
21© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
22© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
pthread APIs
Can be categorized as
Thread Management
Creating, Detaching, Joining, etc
Current Session will focus on this
Thread Communication & Synchronization
Mutex, Conditional Variables, RW Locks, etc
Would be focus of our Next Session
23© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
API Naming Conventions
Function Prefix Functional Group
pthread_ Thread & other Miscellaneous operations
pthread_attr_ Thread attribute operations
pthread_key_ Thread-specific private data operations
pthread_mutex_ Mutex operations
pthread_mutex_attr_ Mutex attribute operations
pthread_cond_ Condition variable operations
pthread_condattr_ Condition variable attribute operations
pthread_rwlock_ Read/write lock operations
pthread_barrier_ Synchronization barrier operations
24© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
pthread Management APIs
Thread Operations
pthread_create
pthread_join
pthread_exit
pthread_cancel
pthread_cleanup_push
pthread_cleanup_pop
Thread Attribute Operations
pthread_attr_*
Thread-specific Data Operations
pthread_key_*
25© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
26© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
27© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
28© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
29© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
30© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
31© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
32© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
33© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
34© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
35© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
36© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
37© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
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
38© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
What all have we learnt?
Threads Overview
W's & How's of Threads
Comparison with Processes
Models for Threaded Programs
Possible Thread Implementations
Threads Programming in Linux: NPTL
Thread Management
Thread Attributes
Thread-specific Data
39© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
All Rights Reserved.
Any Queries?

Más contenido relacionado

La actualidad más candente (20)

Block Drivers
Block DriversBlock Drivers
Block Drivers
 
Introduction to Linux
Introduction to LinuxIntroduction to Linux
Introduction to Linux
 
Signals
SignalsSignals
Signals
 
Linux Memory Management
Linux Memory ManagementLinux Memory Management
Linux Memory Management
 
Embedded Storage Management
Embedded Storage ManagementEmbedded Storage Management
Embedded Storage Management
 
Timers
TimersTimers
Timers
 
Toolchain
ToolchainToolchain
Toolchain
 
Architecture Porting
Architecture PortingArchitecture Porting
Architecture Porting
 
Linux User Space Debugging & Profiling
Linux User Space Debugging & ProfilingLinux User Space Debugging & Profiling
Linux User Space Debugging & Profiling
 
Processes
ProcessesProcesses
Processes
 
Kernel Debugging & Profiling
Kernel Debugging & ProfilingKernel Debugging & Profiling
Kernel Debugging & Profiling
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
Character Drivers
Character DriversCharacter Drivers
Character Drivers
 
Mobile Hacking using Linux Drivers
Mobile Hacking using Linux DriversMobile Hacking using Linux Drivers
Mobile Hacking using Linux Drivers
 
PCI Drivers
PCI DriversPCI Drivers
PCI Drivers
 
Linux Kernel Overview
Linux Kernel OverviewLinux Kernel Overview
Linux Kernel Overview
 
Low-level Accesses
Low-level AccessesLow-level Accesses
Low-level Accesses
 
File System Modules
File System ModulesFile System Modules
File System Modules
 
Kernel Programming
Kernel ProgrammingKernel Programming
Kernel Programming
 
Introduction to Linux Drivers
Introduction to Linux DriversIntroduction to Linux Drivers
Introduction to Linux Drivers
 

Destacado (12)

Embedded C
Embedded CEmbedded C
Embedded C
 
Network Drivers
Network DriversNetwork Drivers
Network Drivers
 
Kernel Debugging & Profiling
Kernel Debugging & ProfilingKernel Debugging & Profiling
Kernel Debugging & Profiling
 
References
ReferencesReferences
References
 
Interrupts
InterruptsInterrupts
Interrupts
 
Functional Programming with LISP
Functional Programming with LISPFunctional Programming with LISP
Functional Programming with LISP
 
Bootloaders
BootloadersBootloaders
Bootloaders
 
Board Bringup
Board BringupBoard Bringup
Board Bringup
 
gcc and friends
gcc and friendsgcc and friends
gcc and friends
 
BeagleBone Black Bootloaders
BeagleBone Black BootloadersBeagleBone Black Bootloaders
BeagleBone Black Bootloaders
 
Linux Porting
Linux PortingLinux Porting
Linux Porting
 
File Systems
File SystemsFile Systems
File Systems
 

Similar a Threads

Scaling Streaming - Concepts, Research, Goals
Scaling Streaming - Concepts, Research, GoalsScaling Streaming - Concepts, Research, Goals
Scaling Streaming - Concepts, Research, Goalskamaelian
 
Concurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple SpacesConcurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple Spacesluccastera
 
Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2mona_hakmy
 
Operating System 4
Operating System 4Operating System 4
Operating System 4tech2click
 
Operating Systems R20 Unit 2.pptx
Operating Systems R20 Unit 2.pptxOperating Systems R20 Unit 2.pptx
Operating Systems R20 Unit 2.pptxPrudhvi668506
 
Oo Design And Patterns
Oo Design And PatternsOo Design And Patterns
Oo Design And PatternsAnil Bapat
 
Beyond the RTOS: A Better Way to Design Real-Time Embedded Software
Beyond the RTOS: A Better Way to Design Real-Time Embedded SoftwareBeyond the RTOS: A Better Way to Design Real-Time Embedded Software
Beyond the RTOS: A Better Way to Design Real-Time Embedded SoftwareQuantum Leaps, LLC
 
thread_ multiprocessor_ scheduling_a.ppt
thread_ multiprocessor_ scheduling_a.pptthread_ multiprocessor_ scheduling_a.ppt
thread_ multiprocessor_ scheduling_a.pptnaghamallella
 
Enea Enabling Real-Time in Linux Whitepaper
Enea Enabling Real-Time in Linux WhitepaperEnea Enabling Real-Time in Linux Whitepaper
Enea Enabling Real-Time in Linux WhitepaperEnea Software AB
 
Concurrency, Parallelism And IO
Concurrency,  Parallelism And IOConcurrency,  Parallelism And IO
Concurrency, Parallelism And IOPiyush Katariya
 
Linux Assignment 3
Linux Assignment 3Linux Assignment 3
Linux Assignment 3Diane Allen
 
Collaboration and Grid Technologies
Collaboration and Grid TechnologiesCollaboration and Grid Technologies
Collaboration and Grid TechnologiesVideoguy
 
Evolution of the Windows Kernel Architecture, by Dave Probert
Evolution of the Windows Kernel Architecture, by Dave ProbertEvolution of the Windows Kernel Architecture, by Dave Probert
Evolution of the Windows Kernel Architecture, by Dave Probertyang
 

Similar a Threads (20)

Scaling Streaming - Concepts, Research, Goals
Scaling Streaming - Concepts, Research, GoalsScaling Streaming - Concepts, Research, Goals
Scaling Streaming - Concepts, Research, Goals
 
Concurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple SpacesConcurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple Spaces
 
Topic 4- processes.pptx
Topic 4- processes.pptxTopic 4- processes.pptx
Topic 4- processes.pptx
 
Multithreading by rj
Multithreading by rjMultithreading by rj
Multithreading by rj
 
Wiki 2
Wiki 2Wiki 2
Wiki 2
 
Os Lamothe
Os LamotheOs Lamothe
Os Lamothe
 
Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2
 
Operating System 4
Operating System 4Operating System 4
Operating System 4
 
Operating Systems R20 Unit 2.pptx
Operating Systems R20 Unit 2.pptxOperating Systems R20 Unit 2.pptx
Operating Systems R20 Unit 2.pptx
 
Oo Design And Patterns
Oo Design And PatternsOo Design And Patterns
Oo Design And Patterns
 
Threads
ThreadsThreads
Threads
 
Beyond the RTOS: A Better Way to Design Real-Time Embedded Software
Beyond the RTOS: A Better Way to Design Real-Time Embedded SoftwareBeyond the RTOS: A Better Way to Design Real-Time Embedded Software
Beyond the RTOS: A Better Way to Design Real-Time Embedded Software
 
thread_ multiprocessor_ scheduling_a.ppt
thread_ multiprocessor_ scheduling_a.pptthread_ multiprocessor_ scheduling_a.ppt
thread_ multiprocessor_ scheduling_a.ppt
 
Enea Enabling Real-Time in Linux Whitepaper
Enea Enabling Real-Time in Linux WhitepaperEnea Enabling Real-Time in Linux Whitepaper
Enea Enabling Real-Time in Linux Whitepaper
 
Concurrency, Parallelism And IO
Concurrency,  Parallelism And IOConcurrency,  Parallelism And IO
Concurrency, Parallelism And IO
 
Linux Assignment 3
Linux Assignment 3Linux Assignment 3
Linux Assignment 3
 
Collaboration and Grid Technologies
Collaboration and Grid TechnologiesCollaboration and Grid Technologies
Collaboration and Grid Technologies
 
Chapter 6 os
Chapter 6 osChapter 6 os
Chapter 6 os
 
Oct2009
Oct2009Oct2009
Oct2009
 
Evolution of the Windows Kernel Architecture, by Dave Probert
Evolution of the Windows Kernel Architecture, by Dave ProbertEvolution of the Windows Kernel Architecture, by Dave Probert
Evolution of the Windows Kernel Architecture, by Dave Probert
 

Más de Anil Kumar Pugalia (10)

File System Modules
File System ModulesFile System Modules
File System Modules
 
Processes
ProcessesProcesses
Processes
 
System Calls
System CallsSystem Calls
System Calls
 
Playing with R L C Circuits
Playing with R L C CircuitsPlaying with R L C Circuits
Playing with R L C Circuits
 
Audio Drivers
Audio DriversAudio Drivers
Audio Drivers
 
Video Drivers
Video DriversVideo Drivers
Video Drivers
 
Power of vi
Power of viPower of vi
Power of vi
 
"make" system
"make" system"make" system
"make" system
 
Hardware Design for Software Hackers
Hardware Design for Software HackersHardware Design for Software Hackers
Hardware Design for Software Hackers
 
RPM Building
RPM BuildingRPM Building
RPM Building
 

Último

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Último (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

Threads

  • 1. © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Threads
  • 2. 2© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. What to Expect? Threads Overview W's & How's of Threads Comparison with Processes Models for Threaded Programs Possible Thread Implementations Threads Programming in Linux: NPTL
  • 3. 3© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Recall Why we needed a Process? To execute multiple tasks at a time What else did we get? Process Creation (Copy) Overhead Context Switch Baggage IPC Overheads vs Synchronization Issues Could we do any better? What if we share as much as we can? Reducing Copies, Switches, Communication Overheads That's were the idea of threads popped-up
  • 4. 4© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. So, let's recall a Process What all did it entail? Address Space (Code, Variables, Stack, Heap) Processor State (PC, Registers, …) OS resources in use File descriptors, IPC, Signal states & actions, Shared libraries, ... Scheduling Info, Priority, ... Preemption Info, Process State, … Extras like Process Info: pid, pgid, userid, gid, ... Environment: Working directory, ... What all & How can these be shared?
  • 5. 5© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. How's of Threads Exist within the Process to use its resources Yet be scheduled by the Kernel And run as independent entities By duplicating only the bare essentials Stack & Stack pointer PC & Other Registers Scheduling Properties Policy, Priority, Process / Execution States Set of pending and blocked signals Thread specific Data
  • 6. 6© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. How threads evolved? Result of the dawn of event-driven programs Where flow of control depends on the user input Example: A modern GUI Multiple Windows – Multiple I/Os Multiple Asynchronous Events (menu pull down) Anytime Actions (without blocking) But all with the same Program / Process
  • 7. 7© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 8. 8© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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 Thread Blocking may lead to Process Blocking On a single-threaded Kernel Security because of inherent sharing
  • 9. 9© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Similarities with a Process Scheduled like a Process & Share CPU Only one thread active at a time Execute sequentially on a uni-processor Individual Thread Execution State Independent Stack & Execution Sequence Can create children If one thread is blocked, another can run
  • 10. 10© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Differences from a Process Threads in a Process are not totally independent of one another Have their own registers and stack but in the same address space Also, share global variables, file descriptors, signal handlers, ... Threads are designed to assist one other Processes may or may not assist one another As they may originate from different users
  • 11. 11© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Process vs Thread Process Addr Space func1() { … } func2() { … } ...... main() { ... } g_array g_val text data heap Files Locks Sockets Process ID Group ID User ID main() var2 var1 stack Stack Pointer Program Counter Registers Process Multi-threaded Process func2() var4 var2 thread1 stack Stack Pointer Program Counter Registers func1() var5 var6 var3 Stack Pointer Program Counter Registers thread2 stack
  • 12. 12© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. W's of Threads Same code but different code execution Same process but different process states Same address space but different stack Shared Variables (Data & Heap), Shared File Descriptors, ... Enabling trivial Communication & hence needing Synchronization
  • 13. 13© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. When to use Threading? Tasks with anyone of these criteria Block for potentially long waits, say on I/O Use many CPU cycles, i.e. CPU intensive Must respond to asynchronous events Of indeterminate frequency & duration Are of lesser or greater importance than others Are able to be performed in parallel with others To achieve optimum performance on SMP architectures
  • 14. 14© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Design for Threading Organize the program into discrete, independent tasks which can execute concurrently Example: If routine1 and routine2 can be interchanged, overlapped and/or interleaved in real time, they are candidates for threading routine1 routine2 final routine routine2 routine1 final routine routine2 routine1 final routine routine2 routine1 final routine routine2 routine1 routine2
  • 15. 15© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Models for Threaded Programs Delegation or Manager-Worker Used when tasks could be interleaved Example: Web server accepting & serving requests Two varieties Static worker pool Dynamic worker pool Pipeline Used when tasks could be overlapped Example: GUI application serving various events Peer Used when tasks could be concurrent Example: Individual I/O Processing Threads Producer-Consumer Used when tasks are producers & consumers Example: Manufacturing unit simulation
  • 16. 16© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Thread Safeness Ability of an application to execute multiple threads simultaneously Without "clobbering" shared data Without creating "race" conditions Examples of thread unsafe applications Two threads calling the same function (with side effects), without synchronizing Multiple threads accessing global variables without access protection Application using non-thread-safe libraries or library functions
  • 17. 17© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Thread Implementations Kernel-level Threads Kernel knows & manages threads Maintains global thread tables Operated using system calls User-level Threads Threads implemented in user libraries Operated using library functions Kernel manages them as individual processes
  • 18. 18© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. “Kernel vs User” level Threads Kernel-level Threads User-level Threads Need modification to Kernel Kernel independent Need a full TCB to manage & schedule Simple representation of TCB in User Process Address Space Thread Switching & Synchronization needs Kernel Intervention Thread Switching & Synchronization are mere function calls Slow & Inefficient Fast & Efficient Good for applications that block frequently Needs non-blocking system calls (i.e. multi-threaded kernel) to avoid entire process blocking on a thread blocking Processes with more threads may be given more time Processes get the same time slice irrespective of the number of threads in it LinuxThreads, NPTL GNU Portable Threads (Pth)
  • 19. 19© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Threads Support in Linux Started with no real support except system call clone() New process shares the address space with the parent Used by LinuxThreads to provide 1x1 kernel-level threads library Threads as child processes with different pid, sharing parent's address space ps would show all threads as processes Basically a new (child) process with Copy-On-Write bit turned off Had issues with signal handling Replaced by the NPTL using the same system call clone() With same pid but different second level ids (thread ids) to achieve 1x1 Real “threads in a process”, starting execution from a specified procedure ps would show only one process & threads under it And equally well, using the efficient lwp mechanisms similar to thread libraries Thus, NPTL is kernel-level thread library with close to user-level library efficiency Try “ps m” & clone.c
  • 20. 20© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Native POSIX Thread Library
  • 21. 21© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 22. 22© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. pthread APIs Can be categorized as Thread Management Creating, Detaching, Joining, etc Current Session will focus on this Thread Communication & Synchronization Mutex, Conditional Variables, RW Locks, etc Would be focus of our Next Session
  • 23. 23© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. API Naming Conventions Function Prefix Functional Group pthread_ Thread & other Miscellaneous operations pthread_attr_ Thread attribute operations pthread_key_ Thread-specific private data operations pthread_mutex_ Mutex operations pthread_mutex_attr_ Mutex attribute operations pthread_cond_ Condition variable operations pthread_condattr_ Condition variable attribute operations pthread_rwlock_ Read/write lock operations pthread_barrier_ Synchronization barrier operations
  • 24. 24© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. pthread Management APIs Thread Operations pthread_create pthread_join pthread_exit pthread_cancel pthread_cleanup_push pthread_cleanup_pop Thread Attribute Operations pthread_attr_* Thread-specific Data Operations pthread_key_*
  • 25. 25© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 26. 26© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 27. 27© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 28. 28© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 29. 29© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 30. 30© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 31. 31© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 32. 32© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 33. 33© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 34. 34© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 35. 35© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 36. 36© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 37. 37© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 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
  • 38. 38© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. What all have we learnt? Threads Overview W's & How's of Threads Comparison with Processes Models for Threaded Programs Possible Thread Implementations Threads Programming in Linux: NPTL Thread Management Thread Attributes Thread-specific Data
  • 39. 39© 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved. Any Queries?