0% found this document useful (0 votes)
21 views41 pages

4 Threads

Uploaded by

James
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views41 pages

4 Threads

Uploaded by

James
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

THREADS

 To introduce the notion of a thread—


a fundamental unit of CPU utilization
that forms the basis of multithreaded
computer systems
 To discuss the APIs for the pthreads,
Windows, and Java thread libraries
OBJECTIVE
S  To explore several strategies that
provide implicit threading
 To examine issues related to
multithreaded programming
 To cover operating system support
for threads in Windows and Linux
MOTIVATION
Thread: basic unit of CPU utilization. Comprises
 Thread id
 Program counter
 Register set
 Stack
Threads of a process share
 Code section
 Data section
 Other OS resources (e.g., Open files and signals)
Most modern applications are multithreaded. Threads
run within application.
SINGLE AND MULTITHREADED
PROCESSES
MOTIVATION

 Multiple simultaneous tasks within the application can be implemented


by separate threads
 Update display
 Fetch data
 Spell checking
 Answer a network request
 Can simplify code, increase efficiency
 Kernels are generally multithreaded
MULTITHREADED SERVER
ARCHITECTURE
Consider implications of a single threaded web server with 9,000
requests!!....
 We can create a new process for each received request
 And.. Process creation is time consuming and resource intensive

?
SYNCHRONOUS THREADING ASYNCHRONOUS THREADING
(threads run sequentially) (threads run simultaneously)

• In Solaris, process creation is ~30 times slower than thread creation.


• Context switching is ~5 times slower.
ASYNCHRONOUS/SYNCHRONOUS
THREADING

• Once the parent creates a child thread, the


parent resumes its execution.
Asynchronous • Parent and child execute concurrently.
• Each thread runs independently of every other
threading thread
• Parent thread agnostic to child terminations

• Once the parent creates a child thread it must


Synchronous wait for all child threads to terminate
• Child threads work concurrently, but parent must
threading wait.
(fork-join strategy) • Typically involved significant data sharing
amongst threads.
Responsiveness – may allow continued
execution if part of process is blocked,
especially important for user interfaces

Resource sharing – threads share


(impromptu) resources of process, easier
than shared memory or message passing
BENEFI
Economy – cheaper than process
creation, thread switching lower overhead
TS
than context switching

Scalability – process can take advantage


of multiprocessor architectures
GREAT VIDEO INTRO TO
THREADS

• HTTPS://TINYURL.COM/Y37ASBJQ
MULTICORE
PROGRAMMING

Concurrency supports more than one task making


progress via rapid switching, and only one executes
at any given time.
 In a single processor/core environment, scheduler provides
concurrency
 Concurrency simulates parallelism

Why can there be no true parallelism in a single core environment?


CONCURRENCY VS.
PARALLELISM
 parallelism implies a system can perform more than one task
simultaneously (requires multicore or multiprocessor)
 multithreaded programming takes advantage of multicore or
multiprocessor systems and achieves parallelism…. if….
MULTICORE
PROGRAMMING
Multicore or multiprocessor systems put pressure on both
OS and application programmers.
 Challenges include:
Dividing activities
Balance – ensuring that separate execution is worth the
cost
Data splitting
Data dependency
Testing and debugging – more challenging to debug
concurrent programs than single-threaded applications.
Should software development be taught with increased emphasis on parallel programming?
A HANDLE in Win32 programming is a
token that represents a resource that
is managed by the Windows kernel.
A handle can be to a window, a file,
etc. Handles are simply a way of
identifying a particulate resource that
you want to work with using the
Win32 APIs.
Logical cores enable a single core to do 2 or
more things simultaneously.
This grew out of the early Pentium 4 CPUs
ability to do what was termed Hyper Threading
MULTICORE PROGRAMMING (CONT.)

Types of Parallelism
• Data parallelism – distributes subsets of CPUs have cores as well as
hardware threads
the same data across multiple cores, same
operation on each Consider oracle SPARC T4 with 8
cores, and 8 hardware threads per
• Add up the elements in an array A. Use core
two threads on two cores- subsets of the
same data. Same operation As # of threads grows, so does
architectural support for threading
• Task parallelism – distributing threads
across cores, each thread performing
unique operation
• Perform two distinct statistical operations
on array A. Use two threads on two
cores. Two distinct operations.
(Data may or may not be the same)
USER THREADS AND KERNEL
THREADS
User threads - management done by user-level threads
library

Three primary thread libraries:


• POSIX pthreads (either user-level or kernel level)
• Windows threads (kernel level)
• Java threads (implemented using host system API)

Kernel threads - supported by the kernel

Examples – virtually all general purpose operating systems,


including:
Windows ,Solaris, Linux Tru64 UNIX, Mac OS X
MULTI-THREADING
MODELS
A relationship must exist between user threads and
kernel threads.
• By itself a user thread is just a bunch of data in a user
Many-to-one program.
• Kernel threads are the real threads in the system, so
for a user thread to make progress the user program
One-to-one has to have its scheduler take a user thread and then
run it on a kernel thread.

Many-to-many
Why?
MANY-TO-ONE
 Many user-level threads mapped to single
kernel thread
 Thread management is done efficiently in the
user space by the thread library
 One thread blocking causes all to block
 Multiple threads may not run in parallel on
multicore system because only one user
thread may access the kernel at a time
 Few systems currently use this model
 Example:
 Solaris green threads
ONE-TO-ONE
 Each user-level thread maps to a kernel thread
 Creating a user-level thread creates a kernel thread (cost issue)
 More concurrency than many-to-one – another thread can run
when a thread makes a blocking system call
 More parallelism in multiprocessor environment
 Number of threads per process sometimes restricted due to
overhead
 Examples
• Windows
• Linux
• Solaris 9 and later
MANY-TO-MANY
 Allows many user level threads to be
mapped/multiplexed to many kernel
threads
 Allows the operating system to
create the appropriate number of
kernel threads based on application
or hardware requirements
 Solaris prior to version 9
 Windows with the threadfiber
package
USER TO KERNEL THREAD
MAPPING
Impact on concurrency
Many-to-one allows ‘unlimited’ user thread
• Not true concurrency since only one kernel thread
executes at a time
One-to-one allows greater concurrency but sets limits
on the number of threads
Many-to-many allows ‘unlimited’ user threads and the
kernel threads can run in parallel on a multiprocessor.
THREAD LIBRARIES

Thread Library Provides Programmer With API For


Creating And Managing Threads
Two Primary Ways Of Implementing
• Library Entirely In User Space
Less Overhead To Create A Thread
• Kernel-level Library Supported By The OS
Requires System Call To Kernel Each Time A Thread Is Created.
PTHREADS
 May be provided either as user-level or kernel-level
 A POSIX standard (IEEE 1003.1c) API for thread creation
and synchronization
 Specification, not implementation what’s the
difference?
 API specifies behavior of the thread library,
implementation is up to development of the library
 Common in UNIX operating systems (solaris, linux, mac
OS X)
IMPLICIT THREADING
IMPLICIT THREADING
 Growing in popularity as numbers of threads increase, program
correctness more difficult with explicit threads
 Creation and management of threads done by compilers and run-
time libraries rather than programmers
 Three methods for designing multithreaded programs that can
take advantage of multicore processing through implicit threading:
 Thread pools
 OpenMP
 Grand Central Dispatch
 Other methods include Microsoft threading building blocks (TBB),
java.Util.Concurrent package
THREAD POOLS – WHY?
Earlier web server example:

 Issues with this solution:


 Thread creation still takes time (albeit less than process
creation)
 Threads are discarded after they complete their tasks
 ‘Unlimited’ threads could exhaust CPU or memory.
THREAD POOLS
 Create a number of threads at process startup in a pool where they await work
 Advantages:
• Usually slightly faster to service a request with an existing thread than create a new
thread
• Allows the number of threads in the application(s) to be bound to the size of the
pool
• Separating task to be performed from mechanics of creating task allows different
strategies for running task
• i.e. Tasks could be scheduled to run periodically or after a delay

 Thread pool size can be


• Set heuristically based on system resources and expected concurrent client
requests
• Dynamically adjusted (e.g., Apple’s Grand Central Dispatch)
OPENMP
 Set of compiler directives and an
API for C, C++, FORTRAN
 Provides support for parallel
programming in shared-memory
environments
 Identifies parallel regions –
blocks of code that can run in
parallel
 #Pragma omp parallel
 Create as many threads as there
are cores
OPENMP
 OpenMP supports parallelizing loops.
 To sum the contents of Arrays A and B into C we would
use the following syntax:
#PRAGMA OMP PARALLEL FOR
FOR(I=0;I<N;I++) {

C[I] = A[I] + B[I];

 The work of summing the arrays is divided among the


created threads
GRAND CENTRAL DISPATCH

 Apple technology for Mac OS X and iOS operating systems


 Extensions to C, C++ languages, API, and run-time library
 Allows identification of parallel sections
 Manages most of the details of threading
 Block is in “^{ }” - ˆ{ printf("i am a block"); }
 Blocks placed in dispatch queue
 Assigned to available thread in thread pool when
removed from queue
THREADING ISSUES
Semantics of fork() and exec() system calls in multithreaded
program
 Should fork() duplicate all threads or is new process single-
threaded?
 What if one thread is deducting money from your checking
account?
 Some unix systems (e.G., Solaris) have two versions fork() and
forkall()
 Use fork() when exec() will be called immediately after forking
since exec() will replace the process
 Use forkall() when the new process does not call exec() so the
new process should duplicate all threads.
THREADING ISSUES

Signal: notification of an event occurring


 Synchronous and asynchronous
Thread cancellation of target thread
 Asynchronous or deferred
Thread-local storage
Scheduler activations
SIGNAL HANDLING
Signals are used in UNIX systems to notify a process that a particular
event has occurred.
A signal handler is used to process signals
 A signal is
 Generated by particular event
 Delivered to a process
 Handled by one of two signal handlers:
 Default
 User-defined

 Every signal has default handler that kernel runs when handling
signal
 User-defined signal handler can override default
 For single-threaded process, signal delivered to process
SIGNAL HANDLING
 Where should a signal be delivered for multi-threaded(CONT.)
process?
• Deliver the signal to the thread to which the signal applies
• Deliver the signal to every thread in the process
• Deliver the signal to certain threads in the process
• Assign a specific thread to receive all signals for the process

 Synchronous signals need to be delivered to the thread causing the


signal (e.g., Divide by 0 error)
 Some asynchronous signals should go to all threads (e.g., <Control>
<C>)
 OSs vary in their support
 To specify threads as destination (Windows APC),
 The ability of threads to selectively block signals (some multithread UNIX
systems)
THREAD CANCELLATION
 Terminating a thread before it has finished
 Multiple threads searching a database. When the data item is found by one
thread, the others can be cancelled.
 Pressing the x button on a browser window will cause multiple threads loading
content (each image is loaded by a separate thread) to be cancelled.

 Thread to be canceled is target thread


 Two general approaches:
 Asynchronous cancellation terminates the target thread usually immediately
but not guaranteed to be so
 Problems occur when resources have been allocated to the target thread or
it is updating data shared by other threads
 OS may only reclaim system resources but not all resources
 Deferred cancellation allows the target thread to periodically check if it should
be cancelled
THREAD-LOCAL STORAGE
 Threads share the data of the process and reduces overhead in data sharing.
 Sometimes threads need their own copy of the data.
• Transactions might store their transaction ids in tls
 Thread-local storage (TLS) allows each thread to have its own copy of data
• e.g., Use of errno to specify system error code. If not protected can get
overwritten by another thread
 Useful when you do not have control over the thread creation process (i.E.,
When using a thread pool)
 Different from local variables
• Local variables visible only during single function invocation
• TLS visible across function invocations (useful to save state)
 Similar to static data
• Except that TLS is unique to each thread
WINDOWS THREADS
 Windows implements the windows API – primary API for win 98, win
NT, win 2000, win XP, and win 7
 Implements the one-to-one mapping, kernel-level
 Each thread contains
 A thread id
 Register set representing state of processor
 Separate user and kernel stacks for when thread runs in user mode or
kernel mode
 Private data storage area used by run-time libraries and dynamic link
libraries (dlls)

 The register set, stacks, and private storage area are known as the
context of the thread
LINUX THREADS

Fork()creates processes (shares all parent data


structures)
Clone()creates threads
Linux refers to processes and threads as tasks
Clone()controls what a child shares of the address
space of the parent task (process)
 Flags control behavior
THREADS REVISIT
3 "types" of threads
 User level threads
 Threads which you create in a multi-threaded application

 Kernel threads
 Each acts as a unit to be scheduled by the OS scheduler

 Hardware threads (or CPU threads)


• A single CPU core is represented to the operating system as two cores
• OS schedules two tasks on the two "logical" cores as it would on two physical
cores in a multi-processor system
• The single physical CPU core will switch between the tasks on the two logical
cores as it sees fit
• When one task is stalled waiting for data to be loaded, it switches to the other one
THREADS REVISITED -
HARDWARE THREADS
1. Program issues a LOAD instruction
• If the content of the requested address isn’t in cache, it needs be fetched
from RAM and there’s a delay

2. Without hardware CPU threading, the CPU is idle during this fetch
time.
3. With hardware threading multiple threads of computation are saved
in an internal cpu memory.
4. Instead of waiting, the computer swaps out the current state, swaps
in one ready to go, and keeps executing
5. That swap can start the new thread on the very next CPU cycle

https://www.youtube.com/watch?
v=wnS50lJicXc 5
END

You might also like