CHAPTER 4 - MULTITHREADED PROGRAMMING

Similar documents
Multi-core Programming System Overview

Operating Systems. 05. Threads. Paul Krzyzanowski. Rutgers University. Spring 2015

Kernel comparison of OpenSolaris, Windows Vista and. Linux 2.6

Chapter 6, The Operating System Machine Level

Processes and Non-Preemptive Scheduling. Otto J. Anshus

Kernel Types System Calls. Operating Systems. Autumn 2013 CS4023

Objectives. Chapter 2: Operating-System Structures. Operating System Services (Cont.) Operating System Services. Operating System Services (Cont.

Operating Systems for Parallel Processing Assistent Lecturer Alecu Felician Economic Informatics Department Academy of Economic Studies Bucharest

OPERATING SYSTEM SERVICES

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

CS420: Operating Systems OS Services & System Calls

How To Write A Windows Operating System (Windows) (For Linux) (Windows 2) (Programming) (Operating System) (Permanent) (Powerbook) (Unix) (Amd64) (Win2) (X

CS 377: Operating Systems. Outline. A review of what you ve learned, and how it applies to a real operating system. Lecture 25 - Linux Case Study

BLM 413E - Parallel Programming Lecture 3

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

First-class User Level Threads

Operating System Tutorial

ELEC 377. Operating Systems. Week 1 Class 3

Operating Systems and Networks

Real Time Programming: Concepts

Operating System: Scheduling

Chapter 2: OS Overview

Operating System Structures

Networking Operating Systems (CO32010)

How To Understand The History Of An Operating System

POSIX. RTOSes Part I. POSIX Versions. POSIX Versions (2)


Threads Scheduling on Linux Operating Systems

Components of a Computing System. What is an Operating System? Resources. Abstract Resources. Goals of an OS. System Software

Performance Comparison of RTOS

1 Organization of Operating Systems

Middleware and Distributed Systems. Design of Scalable Servers. Martin v. Löwis. Donnerstag, 16. Februar 12

System Structures. Services Interface Structure

Course Development of Programming for General-Purpose Multicore Processors

Chapter 2 System Structures

CS3600 SYSTEMS AND NETWORKS

Operating Systems OBJECTIVES 7.1 DEFINITION. Chapter 7. Note:

Example of Standard API

Building Applications Using Micro Focus COBOL

Real-Time Systems Prof. Dr. Rajib Mall Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Thomas Fahrig Senior Developer Hypervisor Team. Hypervisor Architecture Terminology Goals Basics Details

Web Server Architectures

Why Threads Are A Bad Idea (for most purposes)

Road Map. Scheduling. Types of Scheduling. Scheduling. CPU Scheduling. Job Scheduling. Dickinson College Computer Science 354 Spring 2010.

Chapter 2: Processes, Threads, and Agents

ODROID Multithreading in Android

Multiprocessor Scheduling and Scheduling in Linux Kernel 2.6

A Comparative Study on Vega-HTTP & Popular Open-source Web-servers

The Xen of Virtualization

Fachbereich Informatik und Elektrotechnik SunSPOT. Ubiquitous Computing. Ubiquitous Computing, Helmut Dispert

Operating System Overview. Otto J. Anshus

PART IV Performance oriented design, Performance testing, Performance tuning & Performance solutions. Outline. Performance oriented design

Operating System Impact on SMT Architecture

Operating System Components

IBM Software Group. Lotus Domino 6.5 Server Enablement

Cloud Computing. Up until now

SYSTEM ecos Embedded Configurable Operating System

The Double-layer Master-Slave Model : A Hybrid Approach to Parallel Programming for Multicore Clusters

Debugging with TotalView

CSE 544 Principles of Database Management Systems. Magdalena Balazinska Fall 2007 Lecture 5 - DBMS Architecture

COS 318: Operating Systems

Effective Computing with SMP Linux

Shared Address Space Computing: Programming

This tutorial will take you through step by step approach while learning Operating System concepts.

Introduction to Virtual Machines

DB2 Connect for NT and the Microsoft Windows NT Load Balancing Service

Middleware. Peter Marwedel TU Dortmund, Informatik 12 Germany. technische universität dortmund. fakultät für informatik informatik 12

Introduction to Cloud Computing

Software design (Cont.)

CSE 120 Principles of Operating Systems. Modules, Interfaces, Structure

Programming real-time systems with C/C++ and POSIX

Chapter 3 Operating-System Structures

Automatic Logging of Operating System Effects to Guide Application-Level Architecture Simulation

Lecture 1 Operating System Overview

Multi-Threading Performance on Commodity Multi-Core Processors

ACTOR-BASED MODEL FOR CONCURRENT PROGRAMMING. Sander Sõnajalg

INTRODUCTION TO COMPUTING CPIT 201 WEEK 13 LECTURE 3

Operatin g Systems: Internals and Design Principle s. Chapter 10 Multiprocessor and Real-Time Scheduling Seventh Edition By William Stallings

CPS221 Lecture: Operating System Structure; Virtual Machines

Replication on Virtual Machines

4.1 Introduction 4.2 Explain the purpose of an operating system Describe characteristics of modern operating systems Control Hardware Access

Introducing PgOpenCL A New PostgreSQL Procedural Language Unlocking the Power of the GPU! By Tim Child

Parallel Algorithm Engineering

Tools Page 1 of 13 ON PROGRAM TRANSLATION. A priori, we have two translation mechanisms available:

CPU Scheduling Outline

Intro to GPU computing. Spring 2015 Mark Silberstein, , Technion 1

CSCI E 98: Managed Environments for the Execution of Programs

Lecture 6: Interrupts. CSC 469H1F Fall 2006 Angela Demke Brown

Linux Process Scheduling Policy

Multi-core architectures. Jernej Barbic , Spring 2007 May 3, 2007

Symmetric Multiprocessing

Part I Courses Syllabus

CEJVM: Cluster Enabled Java Virtual Machine

Software and the Concurrency Revolution

CHAPTER 1 INTRODUCTION

CPU SCHEDULING (CONT D) NESTED SCHEDULING FUNCTIONS

CS222: Systems Programming

Gildart Haase School of Computer Sciences and Engineering

Section 1.4. Java s Magic: Bytecode, Java Virtual Machine, JIT,

Going Linux on Massive Multicore

Transcription:

CHAPTER 4 - MULTITHREADED PROGRAMMING

OBJECTIVES Introduce notion of thread a fundamental unit of CPU utilization forms the basis of multithreaded computer systems Discuss the APIs for the Pthreads, Windows, and Java thread libraries Explore several strategies that provide implicit threading Examine issues related to multithreaded programming OS support for threads in Windows and Linux 1

OVERVIEW 3. 12

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

MOTIVATION Process creation is heavy-weight while thread creation is light-weight Can simplify code, increase efficiency Kernels are generally multithreaded 3. 2

THREAD Basic unit of computation Thread ID Program counter Register set Stack Shares Shares code, data, OS resources with other threads 3. 3

SINGLE AND MULTITHREADED PROCESSES 3. 4

MULTITHREADED SERVER ARCHITECTURE 3. 5

BENEFITS Responsiveness may allow continued execution if part of process is blocked, especially important for user interfaces Resource Sharing threads share resources of process, easier than shared memory or message passing Economy cheaper than process creation, thread switching lower overhead than context switching Scalability process can take advantage of multiprocessor architectures 3. 6

MULTICORE PROGRAMMING 34. 71

MULTICORE PROGRAMMING Multicore or multiprocessor systems putting pressure on programmers, challenges include: Dividing activities Balance Data splitting Data dependency Testing and debugging

PARALLELISM VS CONCURRENCY 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 4. 2

PARALLELISM VS CONCURRENCY Concurrent execution on single-core system: Parallelism on a multi-core system: 4. 3

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 4. 4

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 4. 5

AMDAHL S LAW 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? 4. 6

MULTITHREADING MODELS 45. 71

USER THREADS User threads - management done by user-level threads library Three primary thread libraries: POSIX Pthreads Win32 threads Java threads

KERNEL THREADS Kernel threads - Supported by the Kernel Examples virtually all general purpose operating systems, including: Windows Solaris Linux Tru64 UNIX Mac OS X 5. 2

MULTITHREADING MODELS Many-to-One One-to-One Many-to-Many 5. 34

MANY-TO-ONE

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 5. 5

ONE-TO-ONE 5. 67

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 NT/XP/2000 Linux Solaris 9 and later

MANY-TO-MANY 5. 8

MANY-TO-MANY 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 NT/2000 with the ThreadFiber package 5. 9

TWO-LEVEL MODEL 5. 10

TWO-LEVEL MODEL Similar to M:M, except that it allows a user thread to be bound to kernel thread Examples IRIX HP-UX Tru64 UNIX Solaris 8 and earlier 5. 11

THREAD LIBRARIES 56. 12. 1

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) 6. 2

PTHREADS EXAMPLE # i n c l u d e < p t h r e a d. h > # i n c l u d e < s t d i o. h > i n t s u m ; / * t h i s d a t a i s s h a r e d b y t h e t h r e a d ( s ) * / v o i d * r u n n e r ( v o i d * p a r a m ) ; / * t h r e a d s c a l l t h i s f u n c t i o n * / i n t m a i n ( i n t a r g c, c h a r * a r g v [ ] ) { p t h r e a d _ t t i d ; / * t h e t h r e a d i d e n t i f i e r * / p t h r e a d _ a t t r _ t a t t r ; / * s e t o f t h r e a d a t t r i b u t e s * / i f ( a r g c! = 2 ) { f p r i n t f ( s t d e r r, " u s a g e : a. o u t < i n t e g e r v a l u e > \ n " ) ; r e t u r n - 1 ; } i f ( a t o i ( a r g v [ 1 ] ) < 0 ) { f p r i n t f ( s t d e r r, " % d m u s t b e > = 0 \ n ", a t o i ( a r g v [ 1 ] ) ) ; r e t u r n - 1 ; 6. 3

PTHREADS CODE FOR JOINING 10 THREADS # d e f i n e N U M T H R E A D S 1 0 / * a n a r r a y o f t h r e a d s t o b e j o i n e d u p o n * / p t h r e a d _ t w o r k e r s [ N U M T H R E A D S ] ; f o r ( i n t i = 0 ; i < N U M T H R E A D S ; i + + ) { p t h r e a d _ j o i n ( w o r k e r s [ i ], N U L L ) ; } 6. 4

WIN API MULTITHREADED # i n c l u d e < w i n d o w s. h > # i n c l u d e < s t d i o. h > D W O R D S u m ; / * d a t a i s s h a r e d b y t h e t h r e a d ( s ) * / / * t h e t h r e a d r u n s i n t h i s s e p a r a t e f u n c t i o n * / D W O R D _ W I N A P I S u m m a t i o n ( L P V O I D P a r a m ) { D W O R D _ U p p e r = * ( D W O R D * ) P a r a m ; f o r ( D W O R D i = 0 ; i < = U p p e r ; i + + ) { S u m + = i ; } r e t u r n 0 ; } i n t m a i n ( i n t a r g c, c h a r * a r g v [ ] ) { D W O R D T h r e a d I d ; H A N D L E T h r e a d H a n d l e ; i n t P a r a m ; i f ( a r g c! = 2 ) { 6. 5

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 p u b l i c i n t e r f a c e R u n n a b l e { p u b l i c a b s t r a c t v o i d r u n ( ) ; } 6. 6

JAVA MULTITHREADED PROGRAM c l a s s S u m { p r i v a t e i n t s u m ; p u b l i c i n t g e t S u m ( ) { r e t u r n s u m ; } p u b l i c v o i d s e t S u m ( i n t s u m ) { t h i s. s u m = s u m ; } } 6. 78

JAVA MULTITHREADED PROGRAM c l a s s S u m m a t i o n i m p l e m e n t s R u n n a b l e { p r i v a t e i n t u p p e r ; p r i v a t e S u m s u m V a l u e ; p u b l i c S u m m a t i o n ( i n t u p p e r, S u m s u m V a l u e ) { t h i s. u p p e r = u p p e r ; t h i s. s u m V a l u e = s u m V a l u e ; } p u b l i c v o i d r u n ( ) { i n t s u m = 0 ; f o r ( i n t i = 0 ; i < = u p p e r ; i + + ) s u m + = i ; s u m V a l u e. s e t S u m ( s u m ) ; } }

JAVA MULTITHREADED PROGRAM p u b l i c c l a s s D r i v e r { p u b l i c s t a t i c v o i d m a i n ( S t r i n g [ ] a r g s ) { i f ( a r g s. l e n g t h > 0 ) { i f ( I n t e g e r. p a r s e I n t ( a r g s [ 0 ] ) < 0 ) { S y s t e m. e r r. p r i n t l n ( a r g s [ 0 ] + " m u s t b e > = 0. " ) ; } e l s e { S u m s u m O b j e c t = n e w S u m ( ) ; i n t u p p e r = I n t e g e r. p a r s e I n t ( a r g s [ 0 ] ) ; T h r e a d t h r d = n e w T h r e a d ( n e w S u m m a t i o n ( u p p e r, s u m O b j e c t ) ) ; t h r d. s t a r t ( ) ; t r y { t h r d. j o i n ( ) ; S y s t e m. o u t. p r i n t l n ( " T h e s u m o f " + u p p e r + " i s " + s u m O b j e c t. g e t } c a t c h ( I n t e r r u p t e d E x c e p t i o n i e ) { } } } e l s e { S y s t e m. e r r. p r i n t l n ( " U s a g e : S u m m a t i o n < i n t e g e r v a l u e > " ) ; 6. 9

IMPLICIT THREADING 67. 10. 1

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 7. 2

IMPLICIT THREADING Three methods explored Thread Pools OpenMP Grand Central Dispatch Other methods include Microsoft Threading Building Blocks (TBB), java.util.concurrentpackage

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 7. 3

THREAD POOLS Windows API supports thread pools: D W O R D W I N A P I P o o l F u n c t i o n ( A V O I D P a r a m ) { / * * T h i s f u n c t i o n r u n s a s a s e p a r a t e t h r e a d * / } 7. 45

GPARS i m p o r t s t a t i c g r o o v y x. g p a r s. G P a r s P o o l / / C a l c u l a t e t h e n ' t h f i b o n a c c i n u m b e r d e f f i b o n n a c c i ( n ) { i f ( n < 2 ) { r e t u r n 1 } f i b o n n a c c i ( n - 1 ) + f i b o n n a c c i ( n - 2 ) } G P a r s P o o l. w i t h P o o l { ( 1.. 5 0 ). e a c h P a r a l l e l { i n t i - > d e f t I d = T h r e a d. c u r r e n t T h r e a d ( ). g e t I d ( ) p r i n t l n " $ { i } f i b n u m b e r : $ { f i b o n n a c c i ( i ) } $ { t I d } " } }

OPENMP Set of compiler directives and an API for C, C++, FORTRAN Provides support for parallel programming in sharedmemory environments Identifies parallel regions blocks of code that can run in parallel 7. 6

OPENMP EXAMPLE # i n c l u d e < o m p. h > # i n c l u d e < s t d i o. h > / / C o m p i l e u s i n g : / / g c c - f o p e n m p o m p. c i n t m a i n ( i n t a r g c, c h a r * a r g v [ ] ) { } # p r a g m a o m p p a r a l l e l { p r i n t f ( " I a m a p a r a l l e l r e g i o n. \ n " ) ; } r e t u r n 0 ; 7. 7

OPENMP EXAMPLE # i n c l u d e < o m p. h > # i n c l u d e < s t d i o. h > / / C o m p i l e u s i n g : / / g c c - f o p e n m p o m p 2. c i n t m a i n ( i n t a r g c, c h a r * a r g v [ ] ) { i n t i ; } # p r a g m a o m p p a r a l l e l f o r f o r ( i = 0 ; i < 2 0 ; i + + ) { p r i n t f ( " I a m a p a r a l l e l f o r l o o p : % i. \ n ", i ) ; } r e t u r n 0 ; 7. 8

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 7. 9

GRAND CENTRAL DISPATCH Two types of dispatch queues: serial blocks removed in FIFO order, queue is per process, called main queue Programmers can create additional serial queues within program concurrent removed in FIFO order but several may be removed at a time three system wide queues with priorities low, default, high 7. 10

THREADING ISSUES 78. 11. 1

THREADING ISSUES Semantics of fork()and exec()system calls Signal handling Synchronous and asynchronous Thread cancellation of target thread Asynchronous or deferred Thread-local storage Scheduler Activations

SEMANTICS 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 8. 2

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 8. 3

SIGNAL HANDLING 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 8. 4

SIGNAL HANDLING 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 8. 5

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 8. 6

THREAD CANCELLATION Pthread code to create and cancel a thread: p t h r e a d _ t t i d ; / * C r e a t e t h e t h r e a d * / p t h r e a d _ c r e a t e ( & t i d, 0, w o r k e r, N U L L ) ;... / * C a n c e l t h e t h r e a d * / p t h r e a d _ c a n c e l ( t i d ) ; 8. 7

THREAD CANCELLATION Invoking thread cancellation requests cancellation, but actual cancellation depends on thread state 8. 8

THREAD CANCELLATION 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 8. 9

THREAD-LOCAL STORAGE Thread-local storage (TLS) allows each thread to have its own copy of data Useful when you do not have control over the thread creation process (i.e., when using a thread pool) 8. 10 11

THREAD-LOCAL STORAGE Different from local variables Local variables visible only during single function invocation TLS visible across function invocations Similar to static data TLS is unique to each thread

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? 8. 12

SCHEDULER ACTIVATIONS 8. 13

SCHEDULER ACTIVATIONS 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 8. 14

OPERATING SYSTEM EXAMPLES 89. 15. 1

OPERATING SYSTEM EXAMPLES Windows XP Threads Linux Thread 9. 2

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 9. 3

WINDOWS THREADS 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

WINDOWS THREADS The primary data structures of a thread include: ETHREAD (executive thread block) includes pointer to process to which thread belongs and to KTHREAD, in kernel space KTHREAD (kernel thread block) scheduling and synchronization info, kernel-mode stack, pointer to TEB, in kernel space TEB (thread environment block) thread id, user-mode stack, thread-local storage, in user space 9. 4

WIN XP THREADS DATA STRUCTURES 9. 5

LINUX THREADS Linux refers to them as tasks rather than threads Thread creation is done through clone()system call 9. 67

LINUX THREADS clone()allows a child task to share the address space of the parent task (process) Flags control behavior struct task_structpoints to process data structures (shared or unique)

QUESTIONS 10 9. 81

BONUS Exam question number 2: Process Concept and Multithreaded Programming 10. 2