CS370 Operating Systems

Similar documents
CS370 Operating Systems

CS370 Operating Systems

Chapter 4: Threads. Chapter 4: Threads

CS370 Operating Systems

Chapter 4: Multithreaded Programming

Chapter 4: Threads. Chapter 4: Threads. Overview Multicore Programming Multithreading Models Thread Libraries Implicit Threading Threading Issues

Questions from last time

Chapter 4: Threads. Operating System Concepts 9 th Edit9on

Chapter 4: Threads. Operating System Concepts 9 th Edition

Chapter 4: Threads. Operating System Concepts 9 th Edition

OPERATING SYSTEM. Chapter 4: Threads

CS370 Operating Systems

Threads. What is a thread? Motivation. Single and Multithreaded Processes. Benefits

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

Chapter 4: Multi-Threaded Programming

CS420: Operating Systems

Chapter 5: Threads. Single and Multithreaded Processes

Lecture 4 Threads. (chapter 4)

Operating Systems Prof. Ashok K Agrawala

CSMC 412. Operating Systems Prof. Ashok K Agrawala Ashok Agrawala Set 4. September 2006 CMSC 412 Set 4

CISC2200 Threads Spring 2015

Lecture Contents. 1. Overview. 2. Multithreading Models 3. Examples of Thread Libraries 4. Summary

Multithreaded Programming

Operating Systems 2 nd semester 2016/2017. Chapter 4: Threads

Chapter 4: Threads. Operating System Concepts with Java 8 th Edition

CSE 4/521 Introduction to Operating Systems

Chapter 4: Threads. Chapter 4: Threads

CS 450 Operating System Week 4 Lecture Notes

I.-C. Lin, Assistant Professor. Textbook: Operating System Concepts 8ed CHAPTER 4: MULTITHREADED PROGRAMMING

Chapter 4: Threads. Overview Multithreading Models Threading Issues Pthreads Windows XP Threads Linux Threads Java Threads. Operating System Concepts

Chapter 4: Threads. Operating System Concepts. Silberschatz, Galvin and Gagne

Chapter 4: Multithreaded Programming. Operating System Concepts 8 th Edition,

Chapter 4: Multithreaded Programming

操作系统原理与设计. 第 4 章 Threads( 线程 ) 陈香兰. March 28, 2014 中国科学技术大学计算机学院. 陈香兰 ( 中国科学技术大学计算机学院 ) 操作系统原理与设计 March 28, /

Definition Multithreading Models Threading Issues Pthreads (Unix)

Chapter 5: Threads. Overview Multithreading Models Threading Issues Pthreads Windows XP Threads Linux Threads Java Threads

CSE Opera,ng System Principles

Processes and Threads

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Chapter 4 Threads. Images from Silberschatz 03/12/18. CS460 Pacific University 1

CS307: Operating Systems

Chapter 4: Multithreaded

Chapter 4: Multithreaded Programming Dr. Varin Chouvatut. Operating System Concepts 8 th Edition,

Chapter 4 Multithreaded Programming

Che-Wei Chang Department of Computer Science and Information Engineering, Chang Gung University

COP 4610: Introduction to Operating Systems (Spring 2015) Chapter 4: Threads. Zhi Wang Florida State University

4.8 Summary. Practice Exercises

CSCE 313 Introduction to Computer Systems. Instructor: Dezhen Song

Outline. Threads. Single and Multithreaded Processes. Benefits of Threads. Eike Ritter 1. Modified: October 16, 2012

CSCE 313: Intro to Computer Systems

Chapter 4: Threads. Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads

POSIX threads CS 241. February 17, Copyright University of Illinois CS 241 Staff

Threads. CS 475, Spring 2018 Concurrent & Distributed Systems

Threads. studykorner.org

Concurrency, Thread. Dongkun Shin, SKKU

Exercise (could be a quiz) Solution. Concurrent Programming. Roadmap. Tevfik Koşar. CSE 421/521 - Operating Systems Fall Lecture - IV Threads

Threads. CS3026 Operating Systems Lecture 06

Chapter 5: Processes & Process Concept. Objectives. Process Concept Process Scheduling Operations on Processes. Communication in Client-Server Systems

Chapter 4: Multithreaded Programming

Chapter 4: Multithreaded Programming

Thread. Disclaimer: some slides are adopted from the book authors slides with permission 1

Last class: Today: Thread Background. Thread Systems

Chapter 4: Threads. Operating System Concepts 9 th Edition

CPSC 341 OS & Networks. Threads. Dr. Yingwu Zhu

Chapter 3: Processes. Operating System Concepts 8th Edition

Threads. Today. Next time. Why threads? Thread model & implementation. CPU Scheduling

Threads. To do. Why threads? Thread model & implementation. q q q. q Next time: Synchronization

CS 3305 Intro to Threads. Lecture 6

EPL372 Lab Exercise 2: Threads and pthreads. Εργαστήριο 2. Πέτρος Παναγή

Processes and Threads

COP 4610: Introduction to Operating Systems (Fall 2016) Chapter 4: Threads. Zhi Wang Florida State University

Thread. Operating Systems (Fall/Winter 2018) Yajin Zhou ( Zhejiang University

CSci 4061 Introduction to Operating Systems. (Threads-POSIX)

Threads. CS-3013 Operating Systems Hugh C. Lauer. CS-3013, C-Term 2012 Threads 1

CS510 Operating System Foundations. Jonathan Walpole

CS333 Intro to Operating Systems. Jonathan Walpole

Last Class: CPU Scheduling. Pre-emptive versus non-preemptive schedulers Goals for Scheduling: CS377: Operating Systems.

4. Concurrency via Threads

Process Concept Process in Memory Process State new running waiting ready terminated Diagram of Process State

Agenda Process Concept Process Scheduling Operations on Processes Interprocess Communication 3.2

Multithreading. Reading: Silberschatz chapter 5 Additional Reading: Stallings chapter 4

pthreads CS449 Fall 2017

Chapter 10. Threads. OS Processes: Control and Resources. A process as managed by the operating system groups together:

Semantics of fork() and exec()

Outline. CS4254 Computer Network Architecture and Programming. Introduction 2/4. Introduction 1/4. Dr. Ayman A. Abdel-Hamid.

Lecture 2 Process Management

!! How is a thread different from a process? !! Why are threads useful? !! How can POSIX threads be useful?

CS 475. Process = Address space + one thread of control Concurrent program = multiple threads of control

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

User Space Multithreading. Computer Science, University of Warwick

Preview. What are Pthreads? The Thread ID. The Thread ID. The thread Creation. The thread Creation 10/25/2017

CSE 306/506 Operating Systems Threads. YoungMin Kwon

Threaded Programming. Lecture 9: Alternatives to OpenMP

PThreads in a Nutshell

LSN 13 Linux Concurrency Mechanisms

! How is a thread different from a process? ! Why are threads useful? ! How can POSIX threads be useful?

THREADS. Jo, Heeseung

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Processes, Threads, SMP, and Microkernels

Lecture 4. Threads vs. Processes. fork() Threads. Pthreads. Threads in C. Thread Programming January 21, 2005

Transcription:

CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 2018 Lecture 7 Threads Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1

FAQ How many processes can a core handle? How threads and processes work together? Process has one of more threads What are pipes? Functions, arrays, strings? Special kind of files Where in memory do pipes reside? Who ensures that pipes work as expected? Why ordinary pipes require a parent-child relationship? Pipe example 3

4 Single and Multithreaded Processes

Process vs Thread All threads in a process have same address space (text, data, open files, signals etc.), same global variables Each thread has its own Thread ID Program counter Registers Stack: execution trail, local variables State (running, ready, blocked, terminated) Thread is a schedulable entity 5

Amdahl s Law Identifies performance gains from adding additional cores to an application that has both serial and parallel components S is serial portion (as a fraction) N processing cores Example: 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? 6

Amdahl s Law: Examples How do you find the parallel portions? Example 1: Only person A can cook. Person A cooks, person B eats and then Person C eats. Person A cooks, then both person B and person C eat at the same time. Example 2: Workload: sum of 10 scalars, and sum of two 10 10 matrices Scalars need to be added one after the other (in serial) The elements of the matrices can be added in parallel Single processor: Time = (10 + 100) tadd 100 processors Time = 10 tadd + 100/100 tadd = 11 tadd Speedup = 110/11 = 10 (10% of potential 100 times) 7

User Threads and Kernel Threads User threads - management done by user-level threads library Three primary thread libraries: POSIX Pthreads Windows threads Java threads Kernel threads - Supported by the Kernel Examples virtually all general purpose operating systems, including: Windows Solaris Linux Mac OS X 8

Multithreading Models How do kernel threads support user process threads? Many-to-One One-to-One (now common) Many-to-Many 9

Many-to-One Many user-level threads mapped to single kernel thread (thread library in user space) 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 for Java 1996 GNU Portable Threads 2006 10

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 11

Many-to-Many Model Allows many user level threads to be mapped to smaller or equal number of kernel threads Allows the operating system to create a sufficient number of kernel threads Solaris prior to version 9 2002-3 Windows with the ThreadFiber package NT/2000 12

Two-level Model Similar to M:M, except that it allows a user thread to be bound to kernel thread Examples IRIX -2006 HP-UX Tru64 UNIX Solaris 8 and earlier 13

14 Single and Multithreaded Processes

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 15

Pthreads May be provided either as user-level or kernel-level A POSIX standard (IEEE 1003.1c) API for thread creation and synchronization 1991 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) 16

Some Pthread management functions POSIX function Description pthread_cancel Terminate a thread pthread_create Create a thread pthread_detach Set thread to release resources pthread_exit Exit a thread without exiting process pthread_kill Send a signal to a thread pthread_join Wait for a thread pthread_self Find out own thread ID Return 0 if successful 17

POSIX: Thread creation pthread_create() Automatically makes the thread runnable without a start operation Takes 3 parameters: Points to ID of newly created thread Attributes for the thread Stack size, scheduling information, etc. Name of function that the thread calls when it begins execution with argument /* create the thread */ pthread_create(&tid, &attr, runner, argv[1]); 18

POSIX: Detaching and Joining pthread_detach() Sets internal options to specify that storage for thread can be reclaimed when it exits 1 parameter: Thread ID of the thread to detach Undetached threads don t release resources until Another thread calls pthread_join for them Process exits pthread_join Takes ID of the thread to wait for Suspends calling thread till target terminates Similar to waitpid at the process level pthread_join(tid, NULL); 19

POSIX: Exiting and cancellation If a process calls exit, all threads terminate Call to pthread_exit causes only the calling thread to terminate pthread_exit(0) Threads can force other threads to return through a cancellation mechanism pthread_cancel: takes thread ID of target Depends on type and state of thread 20

Pthreads Example (next 2 slides) This process will have two threads Initial/main thread to execute the main ( ) function. It crates a new thread and waits for it to finish. A new thread that runs function runner ( ) It will get a parameter, an integer, and will compute the sum of all integers from 1 to that number. New thread leaves the result in a global variable sum. The main thread prints the result. 21

#include <pthread.h> #include <stdio.h> Pthreads Example Pt 1 int sum; /* this data is shared by the thread(s) */ void *runner(void *param); /* the thread */ int main(int argc, char *argv[ ]) { pthread_t tid; /* the thread identifier */ pthread_attr_t attr; /* set of attributes for the thread */ if (argc!= 2) { fprintf(stderr,"usage: a.out <integer value>\n"); /*exit(1);*/ return -1; } if (atoi(argv[1]) < 0) { fprintf(stderr,"argument %d must be non-negative\n",atoi(argv[1])); /*exit(1);*/ return -1; } 22

Pthreads Example Pt 2 /* get the default attributes */ pthread_attr_init(&attr); /* create the thread */ pthread_create(&tid, &attr, runner, argv[1]); /* now wait for the thread to exit */ pthread_join(tid, NULL); printf("sum = %d\n", sum); } /* The thread will begin control in this function */ void *runner(void *param) { int i, upper = atoi(param); sum = 0; } if (upper > 0) { } pthread_exit(0); for (i = 1; i <= upper; i++) sum += i; Compile using gcc thrd.c lpthread Execution: %./thrd 4 sum = 10 23

24 Pthreads Code for Joining 10 Threads

In Class Quiz iclicker 25

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 Override its run() method More commonly, implementing the Runnable interface 1. Has 1 method run() 2. Create new Thread class by passing a Runnable object to its constructor 3. start( ) method creates a new thread by calling the run( ) method. 26

27 Java Thread States

Ex: Using Java Threads (1/3) Java version of a multithreaded program that computes summation of a non-negative integer. class Sum { private int sum; public int get() { return sum; } } public void set(int sum) { this.sum = sum; } 28

Ex: Using Java Threads (2/3) class Summation implements Runnable { private int upper; private Sum sumvalue; public Summation(int upper, Sum sumvalue) { if (upper < 0) throw new IllegalArgumentException(); } this.upper = upper; this.sumvalue = sumvalue; public void run() { int sum = 0; for (int i = 0; i <= upper; i++) sum += i; } } sumvalue.set(sum); 29

Ex: Using Java Threads (3/3) public class Driver { public static void main(string[ ] args) { if (args.length!= 1) { System.err.println("Usage Driver <integer>"); System.exit(0); } Sum sumobject = new Sum(); int upper = Integer.parseInt(args[0]); } } Thread worker = new Thread(new Summation(upper, sumobject)); worker.start(); try { A call to worker.join(); run( ) } catch (InterruptedException ie) { } System.out.println("The sum of " + upper + " is " + sumobject.get()); 30

Help Session Help Session Thursday at 5 PM File I/O, Fork( ), Exec( ), System ( ) etc. Needed for HW2 now available. CSB 425 32

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 33

Implicit Threading1: 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. 34

Implicit Threading2: 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 #pragma omp parallel for for(i=0;i<n;i++) { } c[i] = a[i] + b[i]; Run for loop in parallel Compile using gcc -fopenmp openmp.c 35

Implicit Threading#: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 36

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 37

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 38

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 39

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? 40

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_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL); Pthread code to create and cancel a thread: 41

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 42

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) Ex: Each transaction has a thread and a transaction identifier is needed. 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 43