0% found this document useful (0 votes)
16 views39 pages

ch4 New

Chapter 4 discusses the importance and benefits of multithreading in modern applications, highlighting responsiveness, resource sharing, and efficiency. It covers various multithreading models, including many-to-one, one-to-one, and many-to-many, as well as threading issues like signal handling and thread cancellation. The chapter also introduces thread libraries and the differences between user-level and kernel-level threads, emphasizing the challenges and advantages of multicore programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views39 pages

ch4 New

Chapter 4 discusses the importance and benefits of multithreading in modern applications, highlighting responsiveness, resource sharing, and efficiency. It covers various multithreading models, including many-to-one, one-to-one, and many-to-many, as well as threading issues like signal handling and thread cancellation. The chapter also introduces thread libraries and the differences between user-level and kernel-level threads, emphasizing the challenges and advantages of multicore programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Chapter 4: Threads

Chapter 4: Threads
 Overview
 Multithreading Models
 Thread Libraries
 Threading Issues
Motivation

 Most modern applications are multithreaded


 Threads run within application
 Multiple tasks with the application can be implemented by
separate threads
 Update display
 Fetch data
 Spell checking
 Answer a network request
 Process creation is heavy-weight while thread creation is
light-weight
 Can simplify code, increase efficiency
 Kernels are generally multithreaded
Benefits of Multithread Programming

 Responsiveness. Multithreading an interactive application may allow a


program to continue running even if part of it is blocked or is performing a
lengthy operation, thereby increasing responsiveness to the user. For
instance, a multithreaded web browser could still allow user interaction in one
thread while an image was being loaded in another thread.

 Resource sharing. By default, threads share the memory and the resources
of the process to which they belong. The benefit of sharing code and data is
that it allows an application to have several different threads of activity within
the same address space.
Benefits of Multithread Programming (cont..)

 Economy. Allocating memory and resources for process creation is costly.


Because threads share resources of the process to which they belong, it is
more economical to create and context-switch threads. Empirically gauging
the difference in overhead can be difficult, but in general it is much more time
consuming to create and manage processes than threads. In Solaris, for
example, creating a process is about thirty times slower than is creating a
thread, and context switching is about five times slower.
 Utilization of multiprocessor architectures. The benefits of multithreading
can be greatly increased in a multiprocessor architecture, where threads may
be running in parallel on different processors. A single threaded process can
only run on one CPU, no matter how many are available. Multithreading on a
multi-CPU machine increases concurrency.
Multicore Programming

 Multicore or multiprocessor systems putting pressure on


programmers, challenges include:
 Dividing activities
 Balance
 Data splitting
 Data dependency
 Testing and debugging
 Parallelism implies a system can perform more than one task
simultaneously
 Concurrency supports more than one task making progress
 Single processor / core, scheduler providing concurrency
Multicore Programming (Cont.)

 Types of parallelism
 Data parallelism – distributes subsets of the same data
across multiple cores, same operation on each
 Task parallelism – distributing threads across cores, each
thread performing unique operation
 As of threads grows, so does architectural support for threading
 CPUs have cores as well as hardware threads
 Consider Oracle SPARC T4 with 8 cores, and 8 hardware
threads per core
Concurrency vs. Parallelism
 Concurrent execution on single-core system:

 Parallelism on a multi-core system:


Single and Multithreaded Processes
The main difference between a single-threaded process and a
multithreaded process is the number of tasks that can be
performed simultaneously:
Single-threaded process
A process that can only perform one task at a time. In a single-
threaded programming language, code is executed sequentially,
one instruction at a time.
Multithreaded process
A process that can perform multiple tasks simultaneously. In a
multithreaded programming language, multiple threads can be
executed concurrently, with each thread representing a separate
flow of control.
Multithreading can improve the performance and efficiency of a
CPU, as well as the responsiveness of the system. However,
multithreading can also have some disadvantages, including:
Requires inter-process communication (IPC), Requires separate
memory space for each process, May have higher memory
consumption, and May have overhead due to process creation
Cont..
Amdahl’s Law
 Identifies performance gains from adding additional cores to an
application that has both serial and parallel components
 S is serial portion
 N processing cores

 That is, if application is 75% parallel / 25% serial, moving from 1 to 2


cores results in speedup of 1.6 times
 As N approaches infinity, speedup approaches 1 / S

Serial portion of an application has disproportionate effect on


performance gained by adding additional cores

 But does the law take into account contemporary multicore systems?
Multithreading Models

 Many-to-One

 One-to-One

 Many-to-Many
Many-to-One

 Many user-level threads mapped to


single kernel thread
 One thread blocking causes all to block
 Multiple threads may not run in parallel
on muticore system because only one
may be in kernel at a time
 Few systems currently use this model
 Examples:
 Solaris Green Threads
 GNU Portable Threads
One-to-One
 Each user-level thread maps to kernel thread
 Creating a user-level thread creates a kernel thread
 More concurrency than many-to-one
 Number of threads per process sometimes
restricted due to overhead
 Examples
 Windows
 Linux
 Solaris 9 and later
Many-to-Many Model
 Allows many user level threads to be
mapped to many kernel threads
 Allows the operating system to create
a sufficient number of kernel threads
 Solaris prior to version 9
 Windows with the ThreadFiber
package
Thread Libraries

 Thread library provides programmer with API for creating


and managing threads
 Two primary ways of implementing
 Library entirely in user space
 Kernel-level library supported by the OS
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
 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)
User Threads and Kernel Threads

 User threads
Thread management done by user-level threads library
 Three primary thread libraries: ->
-> POSIX Pthreads
-> Win32 threads
-> Java threads
 User-level threads implement in user-level libraries, rather than
via systems calls, so thread switching does not need to call
operating system and to cause interrupt to the kernel.
 In fact, the kernel knows nothing about user-level threads and
manages them as if they were single- threaded processes.
Cont..

 Advantages: The most obvious advantage of this technique is that a


user-level threads package can be implemented on an Operating
System that does not support threads.
Some other advantages are
 User-level threads does not require modification to operating
systems.
 Simple representation: Each thread is represented simply by a PC,
registers, stack and a small control block, all stored in the user
process address space.
 Simple Management: This simply means that creating a thread,
switching between threads and synchronization between threads
can all be done without intervention of the kernel.
 Fast and Efficient: Thread switching is not much more expensive
than a procedure call.
Cont..

 Disadvantages:
 There is a lack of coordination between threads and operating
system kernel. Therefore, process as whole gets one time slice
irrespective of whether process has one thread or 1000 threads
within. It is up to each thread to relinquish control to other threads.
 User-level threads requires non-blocking systems call i.e., a
multithreaded kernel. Otherwise, entire process will blocked in the
kernel, even if there are runable threads left in the processes. For
example, if one thread causes a page fault, the process blocks.

Kernel-Level Threads
 Supported by the Kernel
 Examples: ->Windows XP/2000, ->Solaris , ->Linux, ->Tru64 UNIX,
->Mac OS X
Cont..
 In this method, the kernel knows about and manages the threads. No
runtime system is needed in this case.
 Instead of thread table in each process, the kernel has a thread table
that keeps track of all threads in the system.
 In addition, the kernel also maintains the traditional process table to
keep track of processes. Operating Systems kernel provides system call
to create and manage threads.
Advantages:
 Because kernel has full knowledge of all threads, Scheduler may decide
to give more time to a process having large number of threads than
process having small number of threads. x Kernel- level threads are
especially good for applications that frequently block.
Disadvantages:
 The kernel-level threads are slow and inefficient. For instance, threads
operations are hundreds of times slower than that of user-level threads.
Pthreads Example
Pthreads Example (Cont.)
Pthreads Code for Joining 10 Threads
Windows Multithreaded C Program
Windows Multithreaded C Program (Cont.)
Java Threads

 Java threads are managed by the JVM


 Typically implemented using the threads model provided by
underlying OS
 Java threads may be created by:

 Extending Thread class


 Implementing the Runnable interface
Java Multithreaded Program
Java Multithreaded Program (Cont.)
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 explored
 Thread Pools
 OpenMP
 Grand Central Dispatch
 Other methods include Microsoft Threading Building Blocks
(TBB), java.util.concurrent package
Threading Issues

 Semantics of fork() and exec() system calls


 Signal handling
 Synchronous and asynchronous
 Thread cancellation of target thread
 Asynchronous or deferred
 Thread Pools
 Scheduler Activations
Semantics of fork() and exec()

 Does fork()duplicate only the calling thread or all


threads?
 Some UNIXes have two versions of fork
 exec() usually works as normal – replace the running
process including all threads
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
1. Signal is generated by particular event
2. Signal is delivered to a process
3. Signal is handled by one of two signal handlers:
1. default
2. user-defined
 Every signal has default handler that kernel runs when
handling signal
 User-defined signal handler can override default
 For single-threaded, signal delivered to process
Signal Handling (Cont.)
 Where should a signal be delivered for multi-threaded?
 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
Thread Cancellation
 Terminating a thread before it has finished
 Thread to be canceled is target thread
 Two general approaches:
 Asynchronous cancellation terminates the target thread
immediately
 Deferred cancellation allows the target thread to periodically
check if it should be cancelled
 Pthread code to create and cancel a thread:
Thread Cancellation (Cont.)
 Invoking thread cancellation requests cancellation, but actual
cancellation depends on thread state

 If thread has cancellation disabled, cancellation remains pending


until thread enables it
 Default type is deferred
 Cancellation only occurs when thread reaches cancellation
point
 I.e. pthread_testcancel()
 Then cleanup handler is invoked
 On Linux systems, thread cancellation is handled through signals
Thread Pools
 Create a number of threads 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
 Windows API supports thread pools:
Scheduler Activations
 Both M:M and Two-level models require
communication to maintain the appropriate
number of kernel threads allocated to the
application
 Typically use an intermediate data structure
between user and kernel threads – lightweight
process (LWP)
 Appears to be a virtual processor on which
process can schedule user thread to run
 Each LWP attached to kernel thread
 How many LWPs to create?
 Scheduler activations provide upcalls - a
communication mechanism from the kernel to
the upcall handler in the thread library
 This communication allows an application to
maintain the correct number kernel threads
End of Chapter 4

You might also like