SlideShare a Scribd company logo
1 of 21
Download to read offline
Threads
Beuth Hochschule

Summer Term 2014

!
Pictures (C) W. Stallings, if not stated otherwise
Operating Systems I PT / FF 2014
Process Concept
• Classically, processes are executed programs that have ...

• Resource Ownership
• Process includes a virtual address space to hold the process image

• Operating system prevents unwanted interference between processes 

• Scheduling/Execution
• Process follows an execution path that may be interleaved with other processes

• Process has an execution state (Running, Ready, etc.) and a dispatching priority
and is scheduled and dispatched by the operating system

• Today, the unit of dispatching is referred to as a thread or lightweight process

• The unit of resource ownership remains the process or task
2
Operating Systems I PT / FF 2014
Single and Multithreaded Processes
3
code% data% files%
registers% stack%
Thread'
code% data% files%
registers%
stack%
Thread'
stack%
registers%
stack%
registers%
Thread' Thread'
Operating Systems I PT / FF 2014
Control Blocks
• Information associated with each process: Process Control Block
• Memory management information

• Accounting information

• Information associated with each thread: Thread Control Block
• Program counter

• CPU registers

• CPU scheduling information

• Pending I/O information
4
Operating Systems I PT / FF 2014
Control Blocks
5
20
Program'Counter'
Parent'PID'
…'
Handle'Table'
Process'ID'(PID)'
Registers'
Next'Process'Block'
Image'File'Name'
PCB'
List'of'Thread'
Control'Blocks'
List'of'open'files'
…'
Next'TCB'
…'
Thread'Control'Block'(TCB)'
Operating Systems I PT / FF 2014
Multithreading
• Each thread has

• An execution state (Running, Ready, etc.)

• Saved thread context when not running

• An execution stack

• Some per-thread static storage for local variables

• Access to the memory and resources of its 

process (all threads of a process share this)

• Suspending a process involves suspending 

all threads of the process 

• Termination of a process terminates all threads 

within the process
6
Operating Systems I PT / FF 2014
Multithreading
7
• Advantages
• Better responsiveness - dedicated threads for handling user events

• Simpler resource sharing - all threads in a process share same address space

• Utilization of multiple cores

for parallel execution

• Faster creation and 

termination of activities

• Disadvantages
• Coordinated termination

• Signal and error handling

• Reentrant vs. non-reentrant system calls
Operating Systems I PT / FF 2014
Thread States
• The typical states for a thread are running, ready, blocked

• Typical thread operations associated with a change in thread state are:

• Spawn: a thread within a process may spawn another thread 

• Provides instruction pointer and arguments for the new thread

• New thread gets its own register context and stack space

• Block: a thread needs to wait for an event

• Saving its user registers, program counter, and stack pointers

• Unblock: When the event for which a thread is blocked occurs

• Finish: When a thread completes, its register context and stacks are deallocated.
8
Operating Systems I PT / FF 2014
Thread Dispatching
9
Thread'T1'
execu,ng'
execu,ng'
ready'or'
wai,ng'
Save'state'into'TCB2'
Reload'state'from'TCB1'
Save'state'into'TCB1'
Reload'state'from'TCB2'
Interrupt'or'system'call' Thread'T2'
execu,ng'
Interrupt'or'system'call'
ready'or'
wai,ng'
ready'or'
wai,ng'
Operating Systems I PT / FF 2014
Example: Windows
• The Windows kernel dispatches threads for multi-tasking

• Implementation of 1:1 mapping - „processes do not run, threads run“

• In principle, all threads are equal - no consideration of process in scheduling

• Thread context switch always involves the kernel

• Every process starts with one main thread, may create more

• Per-process data:

• Virtual address space, working set („owned“ physical memory), access token,
handle table for kernel objects, environment strings, command line

• Per-thread data:

• User-mode stack (call frames, arguments), kernel-mode stack, thread-local
storage, scheduling state, thread priority, hardware context, optional access token
10
Operating Systems I PT / FF 2014
Windows - Thread and Process Creation
11
BOOL CreateProcess(
LPCSTR lpApplicationName,
LPSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCSTR lpCurrentDirectory,
LPSTARTUPINFO lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation)
HANDLE CreateThread (

LPSECURITY_ATTRIBUTES lpsa,

DWORD cbStack,

LPTHREAD_START_ROUTINE lpStartAddr,

LPVOID lpvThreadParm,

DWORD fdwCreate,

LPDWORD lpIDThread)
receives thread ID
	 	 DWORD WINAPI
ThreadFunc(LPVOID)
Operating Systems I PT / FF 2014
Windows - Identifiers
• Every process and every thread has an identifier

• In general: “client ID” (debugger shows as “CID”)

• A.K.A. process ID and thread ID, respectively

• Process IDs and thread IDs are in the same “number space”

• IDs are unique among all existing processes and threads

• Might be reused as soon as a process or thread is deleted

• Identify the requesting process or thread to its subsystem “server” process

• Relevant for API calls that need the server’s help

• Visible in PerfMon, Task Manager (for processes), Process Explorer
12
Operating Systems I PT / FF 2014
Windows - Thread Creation and Termination
• Threads start in the kernel, but have a trap frame to return to user mode

• Threads run until:
• The thread returns to the OS

• ExitThread() is called by the thread

• TerminateThread() is called on the thread

• ExitProcess() is called on the process

• When the last thread in a process terminates, the process itself terminates

• Thread continues to exist until last handle is closed (CloseHandle())

• Each thread has suspend count

• Can only execute if suspend count == 0, can be created in suspended state
13
Operating Systems I PT / FF 2014
Windows - Thread Creation
• Flow of CreateThread():

• The thread count in the process object is incremented. 

• An executive thread block (ETHREAD) is created and initialized.

• A thread ID is generated for the new thread. 

• The TEB is set up in the user-mode address space of the process. 

• The user-mode thread start address is stored in the ETHREAD. 

• KeInitThread is called to set up the KTHREAD block.

• Initial and current base priorities are set to the process’s base priority

• Affinity and quantum are set to that of the process. 

• Allocates kernel stack and initializes machine-dependent hardware context
14
Operating Systems I PT / FF 2014
Windows - Thread Termination
• Thread rundown sequence:

• DLL notification, unless TerminateThread() was used

• All handles to Windows User and GDI objects are closed

• Outstanding I/Os are cancelled

• Thread stack is deallocated

• Thread’s exit code changes from STILL_ACTIVE to the specified exit code

• Thread kernel object becomes signaled

• When handle and reference counts == 0, thread object deleted

• If last thread in process, process exits
15
Operating Systems I PT / FF 2014
Windows - Thread States
• Init: The thread is being created.

• Ready: The thread is waiting to be assigned to a CPU.

• Running: The thread’s instructions are being executed.

• Waiting: The thread is waiting for some event to occur.

• Terminated: The thread has finished execution.
16
init$
ready$
wai+ng$
running$
terminated$
scheduler$
dispatch$
wai+ng$for$
I/O$or$event$
I/O$or$event$
comple+on$
interrupt$$
quantum$expired$
admi<ed$ exit$
Operating Systems I PT / FF 2014
Linux Threads
• No explicit distinguishing between
threads and processes

• User-level threads are mapped to 

kernel tasks

• User threads in the same user process
share the same thread group ID

• Enables resource sharing, avoids
context switch on dispatching

• clone() as extended version of fork()

• On cloning, decision about sharing of
memory, file handles, a.s.o. is made

• Thread libraries use this capability
17
CLONE_CLEARID Clear the task ID.
CLONE_DETACHED The parent does not want a SIGCHLD signal sent on exit.
CLONE_FILES Shares the table that identifies the open files.
CLONE_FS Shares the table that identifies the root directory and the current
working directory, as well as the value of the bit mask used to mask the
initial file permissions of a new file.
CLONE_IDLETASK Set PID to zero, which refers to an idle task. The idle task is employed
when all available tasks are blocked waiting for resources.
CLONE_NEWNS Create a new namespace for the child.
CLONE_PARENT Caller and new task share the same parent process.
CLONE_PTRACE If the parent process is being traced, the child process will also be
traced.
CLONE_SETTID Write the TID back to user space.
CLONE_SETTLS Create a new TLS for the child.
CLONE_SIGHAND Shares the table that identifies the signal handlers.
CLONE_SYSVSEM Shares System V SEM_UNDO semantics.
CLONE_THREAD Inserts this process into the same thread group of the parent. If this flag
is true, it implicitly enforces CLONE_PARENT.
CLONE_VFORK If set, the parent does not get scheduled for execution until the child
invokes the execve() system call.
CLONE_VM Shares the address space (memory descriptor and all page tables).
Operating Systems I PT / FF 2014
Linux Threads
• Thread group ID (TGID) and thread ID (TID) are stored in task structure of the kernel

• Processes with threads have identical PID and TGID

• Linux has distinct kernel threads

• Only executed in kernel mode, typically needs access to kernel data structures

• Can wait for events to occur, e.g. USB hotplugging

• Example: ps -eLf (watch for square brackets, LWP equals thread in the output)
18
Operating Systems I PT / FF 2014
POSIX Threads
• POSIX standardized (IEEE 1003.1c) API for thread creation and synchronization

• API specifies behavior of the thread library, not an implementation

• Thread creation and termination, stack management

• Synchronization between threads

• Scheduling hints

• Thread-local storage

• Implemented on many UNIX operating systems to allow portable concurrent C code

• Windows: Services for Unix (SFU) implement pthreads on Windows

• Linux 2.6: Native POSIX Thread Library (NPTL) implementation of pthreads
19
20
#include <pthread.h>!
#include <stdio.h>!
#include <string.h>!
#include <unistd.h>!
!
void * hello_thread( void *arg ) {!
! printf( "hello " ); return( 0 ); }!
!
void * world_thread( void *arg ) {!
int n;!
! pthread_t!tid!= (pthread_t) arg;!
! if ( n = pthread_join( tid, NULL ) ) {!
! ! fprintf( stderr, "pthread_join: %sn", strerror( n ) );!
! ! return( NULL ); }!
! printf( "worldn" );!
! pthread_exit( 0 ); }!
!
int main( int argc, char *argv[] ) {!
! int!n;!
! pthread_t!htid, wtid;!
! if ( n = pthread_create( &htid, NULL, hello_thread, NULL ) ) {!
! ! fprintf( stderr, "pthread_create: %sn", strerror( n ) );!
! ! return( 1 ); }!
!
! if ( n = pthread_create( &wtid, NULL, world_thread, (void *) htid ) ) {!
! ! fprintf( stderr, "pthread_create: %sn", strerror( n ) );!
! ! return( 1 ); }!
!
! if ( n = pthread_join( wtid, NULL ) ) {!
! ! fprintf( stderr, "pthread_join: %sn", strerror( n ) );!
! ! return( 1 ); }!
! return( 0 ); }
Operating Systems I PT / FF 2014
MacOS X - Grand Central Dispatch (GCD)
• Provides a pool of available threads

• Portions of applications (blocks) can be dispatched independently

• Blocks are lightweigt to create and queue

• Operating system dispatches available blocks on given processors

• GCD provides system queues used by the application,

private queues are possible

• Queues are either concurrent or serial, latter act as lock replacement

• Blocks can be associated with an event source (timer, socket, file descriptor)

• Similar solutions available for other systems
21

More Related Content

What's hot

Software engineering critical systems
Software engineering   critical systemsSoftware engineering   critical systems
Software engineering critical systemsDr. Loganathan R
 
Operating System Process Synchronization
Operating System Process SynchronizationOperating System Process Synchronization
Operating System Process SynchronizationHaziq Naeem
 
INTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptxINTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptxLECO9
 
Operating system 22 threading issues
Operating system 22 threading issuesOperating system 22 threading issues
Operating system 22 threading issuesVaibhav Khanna
 
Mca ii os u-1 introduction to os
Mca  ii  os u-1 introduction to osMca  ii  os u-1 introduction to os
Mca ii os u-1 introduction to osRai University
 
Segmentation in Operating Systems.
Segmentation in Operating Systems.Segmentation in Operating Systems.
Segmentation in Operating Systems.Muhammad SiRaj Munir
 
Real-Time Scheduling
Real-Time SchedulingReal-Time Scheduling
Real-Time Schedulingsathish sak
 
Dead Lock in operating system
Dead Lock in operating systemDead Lock in operating system
Dead Lock in operating systemAli Haider
 
Process management in os
Process management in osProcess management in os
Process management in osMiong Lazaro
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process CommunicationAdeel Rasheed
 
Advanced Operating System- Introduction
Advanced Operating System- IntroductionAdvanced Operating System- Introduction
Advanced Operating System- IntroductionDebasis Das
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in javasharma230399
 

What's hot (20)

Os Threads
Os ThreadsOs Threads
Os Threads
 
Software engineering critical systems
Software engineering   critical systemsSoftware engineering   critical systems
Software engineering critical systems
 
Operating System Process Synchronization
Operating System Process SynchronizationOperating System Process Synchronization
Operating System Process Synchronization
 
Thread
ThreadThread
Thread
 
Input output streams
Input output streamsInput output streams
Input output streams
 
CPU Scheduling Algorithms
CPU Scheduling AlgorithmsCPU Scheduling Algorithms
CPU Scheduling Algorithms
 
INTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptxINTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptx
 
Operating system 22 threading issues
Operating system 22 threading issuesOperating system 22 threading issues
Operating system 22 threading issues
 
Mca ii os u-1 introduction to os
Mca  ii  os u-1 introduction to osMca  ii  os u-1 introduction to os
Mca ii os u-1 introduction to os
 
Segmentation in Operating Systems.
Segmentation in Operating Systems.Segmentation in Operating Systems.
Segmentation in Operating Systems.
 
4.2 PHP Function
4.2 PHP Function4.2 PHP Function
4.2 PHP Function
 
Real-Time Scheduling
Real-Time SchedulingReal-Time Scheduling
Real-Time Scheduling
 
Dead Lock in operating system
Dead Lock in operating systemDead Lock in operating system
Dead Lock in operating system
 
Process management in os
Process management in osProcess management in os
Process management in os
 
Lecture 5 process concept
Lecture 5   process conceptLecture 5   process concept
Lecture 5 process concept
 
7 Deadlocks
7 Deadlocks7 Deadlocks
7 Deadlocks
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
 
Thread
ThreadThread
Thread
 
Advanced Operating System- Introduction
Advanced Operating System- IntroductionAdvanced Operating System- Introduction
Advanced Operating System- Introduction
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 

Viewers also liked

Operating System-Threads-Galvin
Operating System-Threads-GalvinOperating System-Threads-Galvin
Operating System-Threads-GalvinSonali Chauhan
 
Ch5: Threads (Operating System)
Ch5: Threads (Operating System)Ch5: Threads (Operating System)
Ch5: Threads (Operating System)Ahmar Hashmi
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingguesta40f80
 
Thread management
Thread management Thread management
Thread management Ayaan Adeel
 
Thread scheduling in Operating Systems
Thread scheduling in Operating SystemsThread scheduling in Operating Systems
Thread scheduling in Operating SystemsNitish Gulati
 
SSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingSSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingDavid Evans
 
Process and Threads in Linux - PPT
Process and Threads in Linux - PPTProcess and Threads in Linux - PPT
Process and Threads in Linux - PPTQUONTRASOLUTIONS
 
Inventing the Future
Inventing the FutureInventing the Future
Inventing the FutureDavid Evans
 
Once Upon a Process
Once Upon a ProcessOnce Upon a Process
Once Upon a ProcessDavid Evans
 
Multithreading: Exploiting Thread-Level Parallelism to Improve Uniprocessor ...
Multithreading: Exploiting Thread-Level  Parallelism to Improve Uniprocessor ...Multithreading: Exploiting Thread-Level  Parallelism to Improve Uniprocessor ...
Multithreading: Exploiting Thread-Level Parallelism to Improve Uniprocessor ...Ahmed kasim
 
Invent the Future (Operating Systems in 2029)
Invent the Future (Operating Systems in 2029)Invent the Future (Operating Systems in 2029)
Invent the Future (Operating Systems in 2029)David Evans
 

Viewers also liked (20)

Operating System-Threads-Galvin
Operating System-Threads-GalvinOperating System-Threads-Galvin
Operating System-Threads-Galvin
 
Threads
ThreadsThreads
Threads
 
Ch5: Threads (Operating System)
Ch5: Threads (Operating System)Ch5: Threads (Operating System)
Ch5: Threads (Operating System)
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
 
Thread management
Thread management Thread management
Thread management
 
Thread scheduling in Operating Systems
Thread scheduling in Operating SystemsThread scheduling in Operating Systems
Thread scheduling in Operating Systems
 
4 threads
4 threads4 threads
4 threads
 
Scheduling
SchedulingScheduling
Scheduling
 
SSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingSSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and Scheduling
 
Process and Threads in Linux - PPT
Process and Threads in Linux - PPTProcess and Threads in Linux - PPT
Process and Threads in Linux - PPT
 
Main Memory
Main MemoryMain Memory
Main Memory
 
Inventing the Future
Inventing the FutureInventing the Future
Inventing the Future
 
Once Upon a Process
Once Upon a ProcessOnce Upon a Process
Once Upon a Process
 
OS - Thread
OS - ThreadOS - Thread
OS - Thread
 
Multithreading: Exploiting Thread-Level Parallelism to Improve Uniprocessor ...
Multithreading: Exploiting Thread-Level  Parallelism to Improve Uniprocessor ...Multithreading: Exploiting Thread-Level  Parallelism to Improve Uniprocessor ...
Multithreading: Exploiting Thread-Level Parallelism to Improve Uniprocessor ...
 
Linux Programming
Linux ProgrammingLinux Programming
Linux Programming
 
2's complement
2's complement2's complement
2's complement
 
Representation of Negative Numbers
Representation of Negative NumbersRepresentation of Negative Numbers
Representation of Negative Numbers
 
Complement
ComplementComplement
Complement
 
Invent the Future (Operating Systems in 2029)
Invent the Future (Operating Systems in 2029)Invent the Future (Operating Systems in 2029)
Invent the Future (Operating Systems in 2029)
 

Similar to Operating Systems 1 (7/12) - Threads

Chapter -2 operating system presentation
Chapter -2 operating system presentationChapter -2 operating system presentation
Chapter -2 operating system presentationchnrketan
 
Os4 2
Os4 2Os4 2
Os4 2issbp
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threadsrchakra
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesHelpWithAssignment.com
 
Operating Systems 1 (6/12) - Processes
Operating Systems 1 (6/12) - ProcessesOperating Systems 1 (6/12) - Processes
Operating Systems 1 (6/12) - ProcessesPeter Tröger
 
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptxWEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptxbabayaga920391
 
Threads and multi threading
Threads and multi threadingThreads and multi threading
Threads and multi threadingAntonio Cesarano
 
System Device Tree and Lopper: Concrete Examples - ELC NA 2022
System Device Tree and Lopper: Concrete Examples - ELC NA 2022System Device Tree and Lopper: Concrete Examples - ELC NA 2022
System Device Tree and Lopper: Concrete Examples - ELC NA 2022Stefano Stabellini
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Aravindharamanan S
 
Linux Char Device Driver
Linux Char Device DriverLinux Char Device Driver
Linux Char Device DriverGary Yeh
 
Multithreaded Programming Part- III.pdf
Multithreaded Programming Part- III.pdfMultithreaded Programming Part- III.pdf
Multithreaded Programming Part- III.pdfHarika Pudugosula
 
Tuning parallelcodeonsolaris005
Tuning parallelcodeonsolaris005Tuning parallelcodeonsolaris005
Tuning parallelcodeonsolaris005dflexer
 
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...CODE BLUE
 
Structure of processes ppt
Structure of processes pptStructure of processes ppt
Structure of processes pptYojana Nanaware
 
Processes, Threads.pptx
Processes, Threads.pptxProcesses, Threads.pptx
Processes, Threads.pptxLECO9
 
Processes, Threads.pptx
Processes, Threads.pptxProcesses, Threads.pptx
Processes, Threads.pptxSKUP1
 

Similar to Operating Systems 1 (7/12) - Threads (20)

Operating System lab
Operating System labOperating System lab
Operating System lab
 
Chapter -2 operating system presentation
Chapter -2 operating system presentationChapter -2 operating system presentation
Chapter -2 operating system presentation
 
Os4 2
Os4 2Os4 2
Os4 2
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - Processes
 
Operating Systems 1 (6/12) - Processes
Operating Systems 1 (6/12) - ProcessesOperating Systems 1 (6/12) - Processes
Operating Systems 1 (6/12) - Processes
 
Scheduling Thread
Scheduling  ThreadScheduling  Thread
Scheduling Thread
 
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptxWEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
 
Threads
ThreadsThreads
Threads
 
Threads and multi threading
Threads and multi threadingThreads and multi threading
Threads and multi threading
 
System Device Tree and Lopper: Concrete Examples - ELC NA 2022
System Device Tree and Lopper: Concrete Examples - ELC NA 2022System Device Tree and Lopper: Concrete Examples - ELC NA 2022
System Device Tree and Lopper: Concrete Examples - ELC NA 2022
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
 
Linux Char Device Driver
Linux Char Device DriverLinux Char Device Driver
Linux Char Device Driver
 
Multithreaded Programming Part- III.pdf
Multithreaded Programming Part- III.pdfMultithreaded Programming Part- III.pdf
Multithreaded Programming Part- III.pdf
 
Tuning parallelcodeonsolaris005
Tuning parallelcodeonsolaris005Tuning parallelcodeonsolaris005
Tuning parallelcodeonsolaris005
 
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...
 
Structure of processes ppt
Structure of processes pptStructure of processes ppt
Structure of processes ppt
 
Processes, Threads.pptx
Processes, Threads.pptxProcesses, Threads.pptx
Processes, Threads.pptx
 
Processes, Threads.pptx
Processes, Threads.pptxProcesses, Threads.pptx
Processes, Threads.pptx
 
Linux Internals - Part II
Linux Internals - Part IILinux Internals - Part II
Linux Internals - Part II
 

More from Peter Tröger

WannaCry - An OS course perspective
WannaCry - An OS course perspectiveWannaCry - An OS course perspective
WannaCry - An OS course perspectivePeter Tröger
 
Cloud Standards and Virtualization
Cloud Standards and VirtualizationCloud Standards and Virtualization
Cloud Standards and VirtualizationPeter Tröger
 
Distributed Resource Management Application API (DRMAA) Version 2
Distributed Resource Management Application API (DRMAA) Version 2Distributed Resource Management Application API (DRMAA) Version 2
Distributed Resource Management Application API (DRMAA) Version 2Peter Tröger
 
OpenSubmit - How to grade 1200 code submissions
OpenSubmit - How to grade 1200 code submissionsOpenSubmit - How to grade 1200 code submissions
OpenSubmit - How to grade 1200 code submissionsPeter Tröger
 
Design of Software for Embedded Systems
Design of Software for Embedded SystemsDesign of Software for Embedded Systems
Design of Software for Embedded SystemsPeter Tröger
 
Humans should not write XML.
Humans should not write XML.Humans should not write XML.
Humans should not write XML.Peter Tröger
 
What activates a bug? A refinement of the Laprie terminology model.
What activates a bug? A refinement of the Laprie terminology model.What activates a bug? A refinement of the Laprie terminology model.
What activates a bug? A refinement of the Laprie terminology model.Peter Tröger
 
Dependable Systems - Summary (16/16)
Dependable Systems - Summary (16/16)Dependable Systems - Summary (16/16)
Dependable Systems - Summary (16/16)Peter Tröger
 
Dependable Systems - Hardware Dependability with Redundancy (14/16)
Dependable Systems - Hardware Dependability with Redundancy (14/16)Dependable Systems - Hardware Dependability with Redundancy (14/16)
Dependable Systems - Hardware Dependability with Redundancy (14/16)Peter Tröger
 
Dependable Systems - System Dependability Evaluation (8/16)
Dependable Systems - System Dependability Evaluation (8/16)Dependable Systems - System Dependability Evaluation (8/16)
Dependable Systems - System Dependability Evaluation (8/16)Peter Tröger
 
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)Peter Tröger
 
Dependable Systems -Software Dependability (15/16)
Dependable Systems -Software Dependability (15/16)Dependable Systems -Software Dependability (15/16)
Dependable Systems -Software Dependability (15/16)Peter Tröger
 
Dependable Systems -Reliability Prediction (9/16)
Dependable Systems -Reliability Prediction (9/16)Dependable Systems -Reliability Prediction (9/16)
Dependable Systems -Reliability Prediction (9/16)Peter Tröger
 
Dependable Systems -Fault Tolerance Patterns (4/16)
Dependable Systems -Fault Tolerance Patterns (4/16)Dependable Systems -Fault Tolerance Patterns (4/16)
Dependable Systems -Fault Tolerance Patterns (4/16)Peter Tröger
 
Dependable Systems - Introduction (1/16)
Dependable Systems - Introduction (1/16)Dependable Systems - Introduction (1/16)
Dependable Systems - Introduction (1/16)Peter Tröger
 
Dependable Systems -Dependability Means (3/16)
Dependable Systems -Dependability Means (3/16)Dependable Systems -Dependability Means (3/16)
Dependable Systems -Dependability Means (3/16)Peter Tröger
 
Dependable Systems - Hardware Dependability with Diagnosis (13/16)
Dependable Systems - Hardware Dependability with Diagnosis (13/16)Dependable Systems - Hardware Dependability with Diagnosis (13/16)
Dependable Systems - Hardware Dependability with Diagnosis (13/16)Peter Tröger
 
Dependable Systems -Dependability Attributes (5/16)
Dependable Systems -Dependability Attributes (5/16)Dependable Systems -Dependability Attributes (5/16)
Dependable Systems -Dependability Attributes (5/16)Peter Tröger
 
Dependable Systems -Dependability Threats (2/16)
Dependable Systems -Dependability Threats (2/16)Dependable Systems -Dependability Threats (2/16)
Dependable Systems -Dependability Threats (2/16)Peter Tröger
 
Verteilte Software-Systeme im Kontext von Industrie 4.0
Verteilte Software-Systeme im Kontext von Industrie 4.0Verteilte Software-Systeme im Kontext von Industrie 4.0
Verteilte Software-Systeme im Kontext von Industrie 4.0Peter Tröger
 

More from Peter Tröger (20)

WannaCry - An OS course perspective
WannaCry - An OS course perspectiveWannaCry - An OS course perspective
WannaCry - An OS course perspective
 
Cloud Standards and Virtualization
Cloud Standards and VirtualizationCloud Standards and Virtualization
Cloud Standards and Virtualization
 
Distributed Resource Management Application API (DRMAA) Version 2
Distributed Resource Management Application API (DRMAA) Version 2Distributed Resource Management Application API (DRMAA) Version 2
Distributed Resource Management Application API (DRMAA) Version 2
 
OpenSubmit - How to grade 1200 code submissions
OpenSubmit - How to grade 1200 code submissionsOpenSubmit - How to grade 1200 code submissions
OpenSubmit - How to grade 1200 code submissions
 
Design of Software for Embedded Systems
Design of Software for Embedded SystemsDesign of Software for Embedded Systems
Design of Software for Embedded Systems
 
Humans should not write XML.
Humans should not write XML.Humans should not write XML.
Humans should not write XML.
 
What activates a bug? A refinement of the Laprie terminology model.
What activates a bug? A refinement of the Laprie terminology model.What activates a bug? A refinement of the Laprie terminology model.
What activates a bug? A refinement of the Laprie terminology model.
 
Dependable Systems - Summary (16/16)
Dependable Systems - Summary (16/16)Dependable Systems - Summary (16/16)
Dependable Systems - Summary (16/16)
 
Dependable Systems - Hardware Dependability with Redundancy (14/16)
Dependable Systems - Hardware Dependability with Redundancy (14/16)Dependable Systems - Hardware Dependability with Redundancy (14/16)
Dependable Systems - Hardware Dependability with Redundancy (14/16)
 
Dependable Systems - System Dependability Evaluation (8/16)
Dependable Systems - System Dependability Evaluation (8/16)Dependable Systems - System Dependability Evaluation (8/16)
Dependable Systems - System Dependability Evaluation (8/16)
 
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)
 
Dependable Systems -Software Dependability (15/16)
Dependable Systems -Software Dependability (15/16)Dependable Systems -Software Dependability (15/16)
Dependable Systems -Software Dependability (15/16)
 
Dependable Systems -Reliability Prediction (9/16)
Dependable Systems -Reliability Prediction (9/16)Dependable Systems -Reliability Prediction (9/16)
Dependable Systems -Reliability Prediction (9/16)
 
Dependable Systems -Fault Tolerance Patterns (4/16)
Dependable Systems -Fault Tolerance Patterns (4/16)Dependable Systems -Fault Tolerance Patterns (4/16)
Dependable Systems -Fault Tolerance Patterns (4/16)
 
Dependable Systems - Introduction (1/16)
Dependable Systems - Introduction (1/16)Dependable Systems - Introduction (1/16)
Dependable Systems - Introduction (1/16)
 
Dependable Systems -Dependability Means (3/16)
Dependable Systems -Dependability Means (3/16)Dependable Systems -Dependability Means (3/16)
Dependable Systems -Dependability Means (3/16)
 
Dependable Systems - Hardware Dependability with Diagnosis (13/16)
Dependable Systems - Hardware Dependability with Diagnosis (13/16)Dependable Systems - Hardware Dependability with Diagnosis (13/16)
Dependable Systems - Hardware Dependability with Diagnosis (13/16)
 
Dependable Systems -Dependability Attributes (5/16)
Dependable Systems -Dependability Attributes (5/16)Dependable Systems -Dependability Attributes (5/16)
Dependable Systems -Dependability Attributes (5/16)
 
Dependable Systems -Dependability Threats (2/16)
Dependable Systems -Dependability Threats (2/16)Dependable Systems -Dependability Threats (2/16)
Dependable Systems -Dependability Threats (2/16)
 
Verteilte Software-Systeme im Kontext von Industrie 4.0
Verteilte Software-Systeme im Kontext von Industrie 4.0Verteilte Software-Systeme im Kontext von Industrie 4.0
Verteilte Software-Systeme im Kontext von Industrie 4.0
 

Recently uploaded

Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...liera silvan
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 

Recently uploaded (20)

Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 

Operating Systems 1 (7/12) - Threads

  • 1. Threads Beuth Hochschule Summer Term 2014 ! Pictures (C) W. Stallings, if not stated otherwise
  • 2. Operating Systems I PT / FF 2014 Process Concept • Classically, processes are executed programs that have ... • Resource Ownership • Process includes a virtual address space to hold the process image • Operating system prevents unwanted interference between processes • Scheduling/Execution • Process follows an execution path that may be interleaved with other processes • Process has an execution state (Running, Ready, etc.) and a dispatching priority and is scheduled and dispatched by the operating system • Today, the unit of dispatching is referred to as a thread or lightweight process • The unit of resource ownership remains the process or task 2
  • 3. Operating Systems I PT / FF 2014 Single and Multithreaded Processes 3 code% data% files% registers% stack% Thread' code% data% files% registers% stack% Thread' stack% registers% stack% registers% Thread' Thread'
  • 4. Operating Systems I PT / FF 2014 Control Blocks • Information associated with each process: Process Control Block • Memory management information • Accounting information • Information associated with each thread: Thread Control Block • Program counter • CPU registers • CPU scheduling information • Pending I/O information 4
  • 5. Operating Systems I PT / FF 2014 Control Blocks 5 20 Program'Counter' Parent'PID' …' Handle'Table' Process'ID'(PID)' Registers' Next'Process'Block' Image'File'Name' PCB' List'of'Thread' Control'Blocks' List'of'open'files' …' Next'TCB' …' Thread'Control'Block'(TCB)'
  • 6. Operating Systems I PT / FF 2014 Multithreading • Each thread has • An execution state (Running, Ready, etc.) • Saved thread context when not running • An execution stack • Some per-thread static storage for local variables • Access to the memory and resources of its 
 process (all threads of a process share this) • Suspending a process involves suspending 
 all threads of the process • Termination of a process terminates all threads 
 within the process 6
  • 7. Operating Systems I PT / FF 2014 Multithreading 7 • Advantages • Better responsiveness - dedicated threads for handling user events • Simpler resource sharing - all threads in a process share same address space • Utilization of multiple cores
 for parallel execution • Faster creation and 
 termination of activities • Disadvantages • Coordinated termination • Signal and error handling • Reentrant vs. non-reentrant system calls
  • 8. Operating Systems I PT / FF 2014 Thread States • The typical states for a thread are running, ready, blocked • Typical thread operations associated with a change in thread state are: • Spawn: a thread within a process may spawn another thread • Provides instruction pointer and arguments for the new thread • New thread gets its own register context and stack space • Block: a thread needs to wait for an event • Saving its user registers, program counter, and stack pointers • Unblock: When the event for which a thread is blocked occurs • Finish: When a thread completes, its register context and stacks are deallocated. 8
  • 9. Operating Systems I PT / FF 2014 Thread Dispatching 9 Thread'T1' execu,ng' execu,ng' ready'or' wai,ng' Save'state'into'TCB2' Reload'state'from'TCB1' Save'state'into'TCB1' Reload'state'from'TCB2' Interrupt'or'system'call' Thread'T2' execu,ng' Interrupt'or'system'call' ready'or' wai,ng' ready'or' wai,ng'
  • 10. Operating Systems I PT / FF 2014 Example: Windows • The Windows kernel dispatches threads for multi-tasking • Implementation of 1:1 mapping - „processes do not run, threads run“ • In principle, all threads are equal - no consideration of process in scheduling • Thread context switch always involves the kernel • Every process starts with one main thread, may create more • Per-process data: • Virtual address space, working set („owned“ physical memory), access token, handle table for kernel objects, environment strings, command line • Per-thread data: • User-mode stack (call frames, arguments), kernel-mode stack, thread-local storage, scheduling state, thread priority, hardware context, optional access token 10
  • 11. Operating Systems I PT / FF 2014 Windows - Thread and Process Creation 11 BOOL CreateProcess( LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFO lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation) HANDLE CreateThread (
 LPSECURITY_ATTRIBUTES lpsa,
 DWORD cbStack,
 LPTHREAD_START_ROUTINE lpStartAddr,
 LPVOID lpvThreadParm,
 DWORD fdwCreate,
 LPDWORD lpIDThread) receives thread ID DWORD WINAPI ThreadFunc(LPVOID)
  • 12. Operating Systems I PT / FF 2014 Windows - Identifiers • Every process and every thread has an identifier • In general: “client ID” (debugger shows as “CID”) • A.K.A. process ID and thread ID, respectively • Process IDs and thread IDs are in the same “number space” • IDs are unique among all existing processes and threads • Might be reused as soon as a process or thread is deleted • Identify the requesting process or thread to its subsystem “server” process • Relevant for API calls that need the server’s help • Visible in PerfMon, Task Manager (for processes), Process Explorer 12
  • 13. Operating Systems I PT / FF 2014 Windows - Thread Creation and Termination • Threads start in the kernel, but have a trap frame to return to user mode • Threads run until: • The thread returns to the OS • ExitThread() is called by the thread • TerminateThread() is called on the thread • ExitProcess() is called on the process • When the last thread in a process terminates, the process itself terminates • Thread continues to exist until last handle is closed (CloseHandle()) • Each thread has suspend count • Can only execute if suspend count == 0, can be created in suspended state 13
  • 14. Operating Systems I PT / FF 2014 Windows - Thread Creation • Flow of CreateThread(): • The thread count in the process object is incremented. • An executive thread block (ETHREAD) is created and initialized. • A thread ID is generated for the new thread. • The TEB is set up in the user-mode address space of the process. • The user-mode thread start address is stored in the ETHREAD. • KeInitThread is called to set up the KTHREAD block. • Initial and current base priorities are set to the process’s base priority • Affinity and quantum are set to that of the process. • Allocates kernel stack and initializes machine-dependent hardware context 14
  • 15. Operating Systems I PT / FF 2014 Windows - Thread Termination • Thread rundown sequence: • DLL notification, unless TerminateThread() was used • All handles to Windows User and GDI objects are closed • Outstanding I/Os are cancelled • Thread stack is deallocated • Thread’s exit code changes from STILL_ACTIVE to the specified exit code • Thread kernel object becomes signaled • When handle and reference counts == 0, thread object deleted • If last thread in process, process exits 15
  • 16. Operating Systems I PT / FF 2014 Windows - Thread States • Init: The thread is being created. • Ready: The thread is waiting to be assigned to a CPU. • Running: The thread’s instructions are being executed. • Waiting: The thread is waiting for some event to occur. • Terminated: The thread has finished execution. 16 init$ ready$ wai+ng$ running$ terminated$ scheduler$ dispatch$ wai+ng$for$ I/O$or$event$ I/O$or$event$ comple+on$ interrupt$$ quantum$expired$ admi<ed$ exit$
  • 17. Operating Systems I PT / FF 2014 Linux Threads • No explicit distinguishing between threads and processes • User-level threads are mapped to 
 kernel tasks • User threads in the same user process share the same thread group ID • Enables resource sharing, avoids context switch on dispatching • clone() as extended version of fork() • On cloning, decision about sharing of memory, file handles, a.s.o. is made • Thread libraries use this capability 17 CLONE_CLEARID Clear the task ID. CLONE_DETACHED The parent does not want a SIGCHLD signal sent on exit. CLONE_FILES Shares the table that identifies the open files. CLONE_FS Shares the table that identifies the root directory and the current working directory, as well as the value of the bit mask used to mask the initial file permissions of a new file. CLONE_IDLETASK Set PID to zero, which refers to an idle task. The idle task is employed when all available tasks are blocked waiting for resources. CLONE_NEWNS Create a new namespace for the child. CLONE_PARENT Caller and new task share the same parent process. CLONE_PTRACE If the parent process is being traced, the child process will also be traced. CLONE_SETTID Write the TID back to user space. CLONE_SETTLS Create a new TLS for the child. CLONE_SIGHAND Shares the table that identifies the signal handlers. CLONE_SYSVSEM Shares System V SEM_UNDO semantics. CLONE_THREAD Inserts this process into the same thread group of the parent. If this flag is true, it implicitly enforces CLONE_PARENT. CLONE_VFORK If set, the parent does not get scheduled for execution until the child invokes the execve() system call. CLONE_VM Shares the address space (memory descriptor and all page tables).
  • 18. Operating Systems I PT / FF 2014 Linux Threads • Thread group ID (TGID) and thread ID (TID) are stored in task structure of the kernel • Processes with threads have identical PID and TGID • Linux has distinct kernel threads • Only executed in kernel mode, typically needs access to kernel data structures • Can wait for events to occur, e.g. USB hotplugging • Example: ps -eLf (watch for square brackets, LWP equals thread in the output) 18
  • 19. Operating Systems I PT / FF 2014 POSIX Threads • POSIX standardized (IEEE 1003.1c) API for thread creation and synchronization • API specifies behavior of the thread library, not an implementation • Thread creation and termination, stack management • Synchronization between threads • Scheduling hints • Thread-local storage • Implemented on many UNIX operating systems to allow portable concurrent C code • Windows: Services for Unix (SFU) implement pthreads on Windows • Linux 2.6: Native POSIX Thread Library (NPTL) implementation of pthreads 19
  • 20. 20 #include <pthread.h>! #include <stdio.h>! #include <string.h>! #include <unistd.h>! ! void * hello_thread( void *arg ) {! ! printf( "hello " ); return( 0 ); }! ! void * world_thread( void *arg ) {! int n;! ! pthread_t!tid!= (pthread_t) arg;! ! if ( n = pthread_join( tid, NULL ) ) {! ! ! fprintf( stderr, "pthread_join: %sn", strerror( n ) );! ! ! return( NULL ); }! ! printf( "worldn" );! ! pthread_exit( 0 ); }! ! int main( int argc, char *argv[] ) {! ! int!n;! ! pthread_t!htid, wtid;! ! if ( n = pthread_create( &htid, NULL, hello_thread, NULL ) ) {! ! ! fprintf( stderr, "pthread_create: %sn", strerror( n ) );! ! ! return( 1 ); }! ! ! if ( n = pthread_create( &wtid, NULL, world_thread, (void *) htid ) ) {! ! ! fprintf( stderr, "pthread_create: %sn", strerror( n ) );! ! ! return( 1 ); }! ! ! if ( n = pthread_join( wtid, NULL ) ) {! ! ! fprintf( stderr, "pthread_join: %sn", strerror( n ) );! ! ! return( 1 ); }! ! return( 0 ); }
  • 21. Operating Systems I PT / FF 2014 MacOS X - Grand Central Dispatch (GCD) • Provides a pool of available threads • Portions of applications (blocks) can be dispatched independently • Blocks are lightweigt to create and queue • Operating system dispatches available blocks on given processors • GCD provides system queues used by the application,
 private queues are possible • Queues are either concurrent or serial, latter act as lock replacement • Blocks can be associated with an event source (timer, socket, file descriptor) • Similar solutions available for other systems 21