Enviar búsqueda
Cargar
Threads
•
15 recomendaciones
•
10,353 vistas
Anil Kumar Pugalia
Seguir
Native POSIX Threads Library in Linux
Leer menos
Leer más
Tecnología
Educación
Denunciar
Compartir
Denunciar
Compartir
1 de 39
Recomendados
Synchronization
Synchronization
Anil Kumar Pugalia
Linux Network Management
Linux Network Management
Anil Kumar Pugalia
Linux File System
Linux File System
Anil Kumar Pugalia
Embedded Software Design
Embedded Software Design
Anil Kumar Pugalia
Introduction to Linux
Introduction to Linux
Anil Kumar Pugalia
Real Time Systems
Real Time Systems
Anil Kumar Pugalia
System Calls
System Calls
Anil Kumar Pugalia
Inter Process Communication
Inter Process Communication
Anil Kumar Pugalia
Recomendados
Synchronization
Synchronization
Anil Kumar Pugalia
Linux Network Management
Linux Network Management
Anil Kumar Pugalia
Linux File System
Linux File System
Anil Kumar Pugalia
Embedded Software Design
Embedded Software Design
Anil Kumar Pugalia
Introduction to Linux
Introduction to Linux
Anil Kumar Pugalia
Real Time Systems
Real Time Systems
Anil Kumar Pugalia
System Calls
System Calls
Anil Kumar Pugalia
Inter Process Communication
Inter Process Communication
Anil Kumar Pugalia
Block Drivers
Block Drivers
Anil Kumar Pugalia
Introduction to Linux
Introduction to Linux
Anil Kumar Pugalia
Signals
Signals
Anil Kumar Pugalia
Linux Memory Management
Linux Memory Management
Anil Kumar Pugalia
Embedded Storage Management
Embedded Storage Management
Anil Kumar Pugalia
Timers
Timers
Anil Kumar Pugalia
Toolchain
Toolchain
Anil Kumar Pugalia
Architecture Porting
Architecture Porting
Anil Kumar Pugalia
Linux User Space Debugging & Profiling
Linux User Space Debugging & Profiling
Anil Kumar Pugalia
Processes
Processes
Anil Kumar Pugalia
Kernel Debugging & Profiling
Kernel Debugging & Profiling
Anil Kumar Pugalia
Shell Scripting
Shell Scripting
Anil Kumar Pugalia
Character Drivers
Character Drivers
Anil Kumar Pugalia
Mobile Hacking using Linux Drivers
Mobile Hacking using Linux Drivers
Anil Kumar Pugalia
PCI Drivers
PCI Drivers
Anil Kumar Pugalia
Linux Kernel Overview
Linux Kernel Overview
Anil Kumar Pugalia
Low-level Accesses
Low-level Accesses
Anil Kumar Pugalia
File System Modules
File System Modules
Anil Kumar Pugalia
Kernel Programming
Kernel Programming
Anil Kumar Pugalia
Introduction to Linux Drivers
Introduction to Linux Drivers
Anil Kumar Pugalia
Embedded C
Embedded C
Anil Kumar Pugalia
Network Drivers
Network Drivers
Anil Kumar Pugalia
Más contenido relacionado
La actualidad más candente
Block Drivers
Block Drivers
Anil Kumar Pugalia
Introduction to Linux
Introduction to Linux
Anil Kumar Pugalia
Signals
Signals
Anil Kumar Pugalia
Linux Memory Management
Linux Memory Management
Anil Kumar Pugalia
Embedded Storage Management
Embedded Storage Management
Anil Kumar Pugalia
Timers
Timers
Anil Kumar Pugalia
Toolchain
Toolchain
Anil Kumar Pugalia
Architecture Porting
Architecture Porting
Anil Kumar Pugalia
Linux User Space Debugging & Profiling
Linux User Space Debugging & Profiling
Anil Kumar Pugalia
Processes
Processes
Anil Kumar Pugalia
Kernel Debugging & Profiling
Kernel Debugging & Profiling
Anil Kumar Pugalia
Shell Scripting
Shell Scripting
Anil Kumar Pugalia
Character Drivers
Character Drivers
Anil Kumar Pugalia
Mobile Hacking using Linux Drivers
Mobile Hacking using Linux Drivers
Anil Kumar Pugalia
PCI Drivers
PCI Drivers
Anil Kumar Pugalia
Linux Kernel Overview
Linux Kernel Overview
Anil Kumar Pugalia
Low-level Accesses
Low-level Accesses
Anil Kumar Pugalia
File System Modules
File System Modules
Anil Kumar Pugalia
Kernel Programming
Kernel Programming
Anil Kumar Pugalia
Introduction to Linux Drivers
Introduction to Linux Drivers
Anil Kumar Pugalia
La actualidad más candente
(20)
Block Drivers
Block Drivers
Introduction to Linux
Introduction to Linux
Signals
Signals
Linux Memory Management
Linux Memory Management
Embedded Storage Management
Embedded Storage Management
Timers
Timers
Toolchain
Toolchain
Architecture Porting
Architecture Porting
Linux User Space Debugging & Profiling
Linux User Space Debugging & Profiling
Processes
Processes
Kernel Debugging & Profiling
Kernel Debugging & Profiling
Shell Scripting
Shell Scripting
Character Drivers
Character Drivers
Mobile Hacking using Linux Drivers
Mobile Hacking using Linux Drivers
PCI Drivers
PCI Drivers
Linux Kernel Overview
Linux Kernel Overview
Low-level Accesses
Low-level Accesses
File System Modules
File System Modules
Kernel Programming
Kernel Programming
Introduction to Linux Drivers
Introduction to Linux Drivers
Destacado
Embedded C
Embedded C
Anil Kumar Pugalia
Network Drivers
Network Drivers
Anil Kumar Pugalia
Kernel Debugging & Profiling
Kernel Debugging & Profiling
Anil Kumar Pugalia
References
References
Anil Kumar Pugalia
Interrupts
Interrupts
Anil Kumar Pugalia
Functional Programming with LISP
Functional Programming with LISP
Anil Kumar Pugalia
Bootloaders
Bootloaders
Anil Kumar Pugalia
Board Bringup
Board Bringup
Anil Kumar Pugalia
gcc and friends
gcc and friends
Anil Kumar Pugalia
BeagleBone Black Bootloaders
BeagleBone Black Bootloaders
SysPlay eLearning Academy for You
Linux Porting
Linux Porting
Anil Kumar Pugalia
File Systems
File Systems
Anil Kumar Pugalia
Destacado
(12)
Embedded C
Embedded C
Network Drivers
Network Drivers
Kernel Debugging & Profiling
Kernel Debugging & Profiling
References
References
Interrupts
Interrupts
Functional Programming with LISP
Functional Programming with LISP
Bootloaders
Bootloaders
Board Bringup
Board Bringup
gcc and friends
gcc and friends
BeagleBone Black Bootloaders
BeagleBone Black Bootloaders
Linux Porting
Linux Porting
File Systems
File Systems
Similar a Threads
Scaling Streaming - Concepts, Research, Goals
Scaling Streaming - Concepts, Research, Goals
kamaelian
Concurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple Spaces
luccastera
Topic 4- processes.pptx
Topic 4- processes.pptx
DanishMahmood23
Multithreading by rj
Multithreading by rj
Shree M.L.Kakadiya MCA mahila college, Amreli
Wiki 2
Wiki 2
Sid Hegde
Os Lamothe
Os Lamothe
oscon2007
Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2
mona_hakmy
Operating System 4
Operating System 4
tech2click
Operating Systems R20 Unit 2.pptx
Operating Systems R20 Unit 2.pptx
Prudhvi668506
Oo Design And Patterns
Oo Design And Patterns
Anil Bapat
Threads
Threads
SURBHI SAROHA
Beyond the RTOS: A Better Way to Design Real-Time Embedded Software
Beyond the RTOS: A Better Way to Design Real-Time Embedded Software
Quantum Leaps, LLC
thread_ multiprocessor_ scheduling_a.ppt
thread_ multiprocessor_ scheduling_a.ppt
naghamallella
Enea Enabling Real-Time in Linux Whitepaper
Enea Enabling Real-Time in Linux Whitepaper
Enea Software AB
Concurrency, Parallelism And IO
Concurrency, Parallelism And IO
Piyush Katariya
Linux Assignment 3
Linux Assignment 3
Diane Allen
Collaboration and Grid Technologies
Collaboration and Grid Technologies
Videoguy
Chapter 6 os
Chapter 6 os
AbDul ThaYyal
Oct2009
Oct2009
guest81ab2b4
Evolution of the Windows Kernel Architecture, by Dave Probert
Evolution of the Windows Kernel Architecture, by Dave Probert
yang
Similar a Threads
(20)
Scaling Streaming - Concepts, Research, Goals
Scaling Streaming - Concepts, Research, Goals
Concurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple Spaces
Topic 4- processes.pptx
Topic 4- processes.pptx
Multithreading by rj
Multithreading by rj
Wiki 2
Wiki 2
Os Lamothe
Os Lamothe
Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2
Operating System 4
Operating System 4
Operating Systems R20 Unit 2.pptx
Operating Systems R20 Unit 2.pptx
Oo Design And Patterns
Oo Design And Patterns
Threads
Threads
Beyond 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.ppt
Enea Enabling Real-Time in Linux Whitepaper
Enea Enabling Real-Time in Linux Whitepaper
Concurrency, Parallelism And IO
Concurrency, Parallelism And IO
Linux Assignment 3
Linux Assignment 3
Collaboration and Grid Technologies
Collaboration and Grid Technologies
Chapter 6 os
Chapter 6 os
Oct2009
Oct2009
Evolution of the Windows Kernel Architecture, by Dave Probert
Evolution of the Windows Kernel Architecture, by Dave Probert
Más de Anil Kumar Pugalia
File System Modules
File System Modules
Anil Kumar Pugalia
Processes
Processes
Anil Kumar Pugalia
System Calls
System Calls
Anil Kumar Pugalia
Playing with R L C Circuits
Playing with R L C Circuits
Anil Kumar Pugalia
Audio Drivers
Audio Drivers
Anil Kumar Pugalia
Video Drivers
Video Drivers
Anil Kumar Pugalia
Power of vi
Power of vi
Anil Kumar Pugalia
"make" system
"make" system
Anil Kumar Pugalia
Hardware Design for Software Hackers
Hardware Design for Software Hackers
Anil Kumar Pugalia
RPM Building
RPM Building
Anil Kumar Pugalia
Más de Anil Kumar Pugalia
(10)
File System Modules
File System Modules
Processes
Processes
System Calls
System Calls
Playing with R L C Circuits
Playing with R L C Circuits
Audio Drivers
Audio Drivers
Video Drivers
Video Drivers
Power of vi
Power of vi
"make" system
"make" system
Hardware Design for Software Hackers
Hardware Design for Software Hackers
RPM Building
RPM Building
Último
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 interpreter
naman860154
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
Paola De la Torre
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
Delhi Call girls
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
Puma Security, LLC
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
hans926745
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
HampshireHUG
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
Maria Levchenko
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
Pooja Nehwal
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
OnBoard
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
Enterprise Knowledge
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
Ridwan Fadjar
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
2toLead Limited
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
Slack Application Development 101 Slides
Slack Application Development 101 Slides
praypatel2
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
soniya singh
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
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.pptx
Malak Abu Hammad
Último
(20)
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 interpreter
Salesforce 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 Men
Breaking 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
04-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 texts
WhatsApp 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.pptx
The 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 Presentation
Tech-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 slide
Slack 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 | Delhi
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 ...
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.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?