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

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

CS333 Intro to Operating Systems. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole

CS533 Concepts of Operating Systems. Jonathan Walpole

CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives

Unix. Threads & Concurrency. Erick Fredj Computer Science The Jerusalem College of Technology

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

Processes, Threads, SMP, and Microkernels

CS 3305 Intro to Threads. Lecture 6

CS 333 Introduction to Operating Systems. Class 4 Concurrent Programming and Synchronization Primitives

POSIX Threads. HUJI Spring 2011

Interprocess Communication and Synchronization

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

Concurrency, Thread. Dongkun Shin, SKKU

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

Processes Prof. James L. Frankel Harvard University. Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved.

ECE 574 Cluster Computing Lecture 8

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

Threads. Threads (continued)

CS 5523 Operating Systems: Midterm II - reivew Instructor: Dr. Tongping Liu Department Computer Science The University of Texas at San Antonio

Introduction to PThreads and Basic Synchronization

Agenda. Process vs Thread. ! POSIX Threads Programming. Picture source:

Questions answered in this lecture: CS 537 Lecture 19 Threads and Cooperation. What s in a process? Organizing a Process

Lec 26: Parallel Processing. Announcements

CS 261 Fall Mike Lam, Professor. Threads

pthreads CS449 Fall 2017

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

CS 333 Introduction to Operating Systems Class 2 OS-Related Hardware & Software The Process Concept

Processes The Process Model. Chapter 2. Processes and Threads. Process Termination. Process Creation

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization

Threads. CS3026 Operating Systems Lecture 06

High Performance Computing Course Notes Shared Memory Parallel Programming

CS240: Programming in C. Lecture 18: PThreads

TCSS 422: OPERATING SYSTEMS

CS399 New Beginnings. Jonathan Walpole

ECE 598 Advanced Operating Systems Lecture 23

Processes. CS3026 Operating Systems Lecture 05

Multithreaded Programming

Processes The Process Model. Chapter 2 Processes and Threads. Process Termination. Process States (1) Process Hierarchies

Pre-lab #2 tutorial. ECE 254 Operating Systems and Systems Programming. May 24, 2012

pthreads Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage)

Chapter 2 Processes and Threads

CS 333 Introduction to Operating Systems. Class 2 OS-Related Hardware & Software The Process Concept

Lecture 5 Threads and Pthreads II

OS 1 st Exam Name Solution St # (Q1) (19 points) True/False. Circle the appropriate choice (there are no trick questions).

Processes and Threads

Recap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack

THREADS. Jo, Heeseung

Parallel Programming with Threads

CMPSC 311- Introduction to Systems Programming Module: Concurrency

Operating systems fundamentals - B06

CSE 153 Design of Operating Systems Fall 2018

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CS 5523 Operating Systems: Thread and Implementation

LSN 13 Linux Concurrency Mechanisms

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

Multicore and Multiprocessor Systems: Part I

Review: Easy Piece 1

CSCE 313 Introduction to Computer Systems. Instructor: Dezhen Song

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

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

CSCE 313: Intro to Computer Systems

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

CSCI4430 Data Communication and Computer Networks. Pthread Programming. ZHANG, Mi Jan. 26, 2017

Concurrent Programming. Concurrent Programming with Processes and Threads

CSE 333 SECTION 9. Threads

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

CS 31: Introduction to Computer Systems : Threads & Synchronization April 16-18, 2019

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

CS 5523: Operating Systems

CS Operating Systems: Threads (SGG 4)

Processes and Threads. Processes and Threads. Processes (2) Processes (1)

Parallel Programming Languages COMP360

Multiprocessors 2007/2008

CMPSC 311- Introduction to Systems Programming Module: Concurrency

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

CISC2200 Threads Spring 2015

Processes & Threads. Today. Next Time. ! Process concept! Process model! Implementing processes! Multiprocessing once again. ! More of the same J

Concurrency. Johan Montelius KTH

OS lpr. www. nfsd gcc emacs ls 1/27/09. Process Management. CS 537 Lecture 3: Processes. Example OS in operation. Why Processes? Simplicity + Speed

Concurrency and Synchronization. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

What is concurrency? Concurrency. What is parallelism? concurrency vs parallelism. Concurrency: (the illusion of) happening at the same time.

A process. the stack

CS 326: Operating Systems. Process Execution. Lecture 5

UNIX Input/Output Buffering

Lecture Topics. Announcements. Today: Threads (Stallings, chapter , 4.6) Next: Concurrency (Stallings, chapter , 5.

Q1. State True/false with jusification if the answer is false:

Introduction to OS Processes in Unix, Linux, and Windows MOS 2.1 Mahmoud El-Gayyar

4.8 Summary. Practice Exercises

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Threads. lightweight processes

Preview. The Thread Model Motivation of Threads Benefits of Threads Implementation of Thread

Operating Systems & Concurrency: Process Concepts

518 Lecture Notes Week 3

Computer Systems Laboratory Sungkyunkwan University

Processes. Johan Montelius KTH

Chapter 4: Processes. Process Concept

CSE 380 Computer Operating Systems. Instructor: Insup Lee. University of Pennsylvania Fall 2003

CS 153 Lab4 and 5. Kishore Kumar Pusukuri. Kishore Kumar Pusukuri CS 153 Lab4 and 5

Transcription:

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

The Process Concept 2

The Process Concept Process a program in execution Program Process description of how to perform an activity instructions and static data values a snapshot of a program in execution memory (program instructions, static and dynamic data values) CPU state (registers, PC, SP, etc) operating system state (open files, accounting statistics etc) 3

Why use the process abstraction? Multiprogramming of four programs in the same address space Conceptual model of 4 independent, sequential processes Only one program active at any instant 4

The role of the scheduler Lowest layer of process-structured OS handles interrupts & scheduling of processes Sequential processes only exist above that layer 5

Process states Possible process states running blocked ready 6

How do processes get created? Principal events that cause process creation System initialization Initiation of a batch job User request to create a new process Execution of a process creation system call from another process 7

Process hierarchies Parent creates a child process, special system calls for communicating with and waiting for child processes each process is assigned a unique identifying number or process ID (PID) Child processes can create their own child processes Forms a hierarchy UNIX calls this a "process group" 8

Process creation in UNIX All processes have a unique process id getpid(), getppid() system calls allow processes to get their information Process creation fork() system call creates a copy of a process and returns in both processes (parent and child), but with a different return value exec() replaces an address space with a new program Process termination, signaling signal(), kill() system calls allow a process to be terminated or have specific signals sent to it 9

Example: process creation in UNIX csh (pid = 22) pid = fork() if (pid == 0) { // child exec(); } else { // parent wait(); } 10

Process creation in UNIX example csh (pid = 22) pid = fork() if (pid == 0) { // child exec(); } else { // parent wait(); } csh (pid = 24) pid = fork() if (pid == 0) { // child exec(); } else { // parent wait(); } 11

Process creation in UNIX example csh (pid = 22) pid = fork() if (pid == 0) { // child exec(); } else { // parent wait(); } csh (pid = 24) pid = fork() if (pid == 0) { // child exec(); } else { // parent wait(); } 12

Process creation in UNIX example csh (pid = 22) pid = fork() if (pid == 0) { // child exec(); } else { // parent wait(); } csh (pid = 24) pid = fork() if (pid == 0) { // child exec(); } else { // parent wait(); } 13

Process creation in UNIX example csh (pid = 22) pid = fork() if (pid == 0) { // child exec(); } else { // parent wait(); } ls (pid = 24) //ls program main(){ //look up dir } 14

Process creation (fork) Fork creates a new process by copying the calling process The new process has its own memory address space (copied from parent) Instructions Data Stack Register set (copied from parent) Process table entry in the OS 15

Threads 16

Threads Processes have the following components: an address space a collection of operating system state a CPU context or thread of control On multiprocessor systems, with several CPUs, it would make sense for a process to have several CPU contexts (threads of control) Thread fork creates new thread not memory space Multiple threads of control could run in the same memory space on a single CPU system too! 17

Threads Threads share a process address space with zero or more other threads Threads have their own CPU context PC, SP, register state, stack A traditional process can be viewed as a memory address space with a single thread 18

Single thread state within a process 19

Multiple threads in an address space 20

What is a thread? A thread executes a stream of instructions it is an abstraction for control-flow Practically, it is a processor context and stack Allocated a CPU by a scheduler Executes in the context of a memory address space 21

Summary of private per-thread state Things that define the state of a particular flow of control in an executing program: Stack (local variables) Stack pointer Registers Scheduling properties (i.e., priority) 22

Shared state among threads Things that relate to an instance of an executing program (that may have multiple threads) User ID, group ID, process ID Address space Text Data (off-stack global variables) Heap (dynamic data) Open files, sockets, locks Important: Changes made to shared state by one thread will be visible to the others Reading and writing memory locations requires synchronization! a major topic for later 23

How do you program using threads? Split program into routines to execute in parallel True or pseudo (interleaved) parallelism Alternative strategies for executing multiple rountines 24

Why program using threads? Utilize multiple CPU s concurrently Low cost communication via shared memory Overlap computation and blocking on a single CPU Blocking due to I/O Computation and communication Handle asynchronous events 25

Thread usage A word processor with three threads 26

Processes versus threads - example A WWW process GET / HTTP/1.0 HTTPD disk 27

Processes versus threads - example A WWW process GET / HTTP/1.0 HTTPD disk Why is this not a good web server design? 28

Processes versus threads - example A WWW process GET / HTTP/1.0 HTTPD HTTPD disk 29

Processes versus threads - example A WWW process GET / HTTP/1.0 HTTPD GET / HTTP/1.0 disk 30

Processes versus threads - example A WWW process GET / HTTP/1.0 HTTPD GET / HTTP/1.0 GET / HTTP/1.0 GET / HTTP/1.0 disk 31

System structuring options Three ways to construct a server 32

Common thread programming models Manager/worker Manager thread handles I/O and assigns work to worker threads Worker threads may be created dynamically, or allocated from a thread-pool Pipeline Each thread handles a different stage of an assembly line Threads hand work off to each other in a producerconsumer relationship 33

What does a typical thread API look like? POSIX standard threads (Pthreads) First thread exists in main(), typically creates the others pthread_create (thread,attr,start_routine,arg) Returns new thread ID in thread Executes routine specified by start_routine with argument specified by arg Exits on return from routine or when told explicitly 34

Thread API (continued) pthread_exit (status) Terminates the thread and returns status to any joining thread pthread_join (threadid,status) Blocks the calling thread until thread specified by threadid terminates Return status from pthread_exit is passed in status One way of synchronizing between threads pthread_yield () Thread gives up the CPU and enters the run queue 35

Using create, join and exit primitives 36

An example Pthreads program #include <pthread.h> #include <stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { printf("\n%d: Hello World!\n", threadid); pthread_exit(null); } int main (int argc, char *argv[]) { pthread_t threads[num_threads]; int rc, t; for(t=0; t<num_threads; t++) { printf("creating thread %d\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc) { printf("error; return code from pthread_create() is %d\n", rc); exit(-1); } } pthread_exit(null); } Program Output Creating thread 0 Creating thread 1 0: Hello World! 1: Hello World! Creating thread 2 Creating thread 3 2: Hello World! 3: Hello World! Creating thread 4 4: Hello World! For more examples see: http://www.llnl.gov/computing/tutorials/pthreads 37

Pros & cons of threads Pros Overlap I/O with computation! Cheaper context switches Better mapping to shared memory multiprocessors Cons Potential thread interactions Complexity of debugging Complexity of multi-threaded programming Backwards compatibility with existing code 38

User-level threads The idea of managing multiple abstract program counters above a single real one can be implemented using privileged or non-privileged code. Threads can be implemented in the OS or at user level User level thread implementations thread scheduler runs as user code (thread library) manages thread contexts in user space The underlying OS sees only a traditional process above 39

Kernel-level threads The thread-switching code is in the kernel 40

User-level threads package The thread-switching code is in user space 41

User-level threads Advantages cheap context switch costs among threads in the same process! A procedure call not a system call! User-programmable scheduling policy Disadvantages How to deal with blocking system calls! How to overlap I/O and computation! 42

Concurrent Programming 43

Concurrent programming Assumptions: Example: Two or more threads Each executes in (pseudo) parallel We can t predict exact running speeds The threads can interact via access to shared variables One thread writes a variable The other thread reads from the same variable Problem non-determinism: The relative order of one thread s reads and the other thread s writes determines the end result! 44

Race conditions What is a race condition? two or more threads have an inconsistent view of a shared memory region (I.e., a variable) Why do race conditions occur? 45

Race conditions A simple multithreaded program with a race: i++; 46

Race conditions A simple multithreaded program with a race:... load i to register; increment register; store register to i;... 47

Race conditions What is a race condition? two or more threads have an inconsistent view of a shared memory region (I.e., a variable) Why do race conditions occur? values of memory locations replicated in registers during execution context switches at arbitrary times during execution threads can see stale memory values in registers 48

Race Conditions Race condition: whenever the output depends on the precise execution order of the processes! What solutions can we apply? prevent context switches by preventing interrupts make threads coordinate with each other to ensure mutual exclusion in accessing critical sections of code 49

Mutual exclusion conditions No two processes simultaneously in critical section No assumptions made about speeds or numbers of CPUs No process running outside its critical section may block another process No process must wait forever to enter its critical section 50

Spare Slides - intended for class 4 51

Critical sections with mutual exclusion 52

How can we enforce mutual exclusion? What about using locks? s solve the problem of exclusive access to shared data. Acquiring a lock prevents concurrent access Expresses intention to enter critical section Assumption: Each each shared data item has an associated lock Every thread sets the right lock before accessing shared data! Every thread releases the lock after it is done! 53

Acquiring and releasing locks Thread B Thread C Thread A Thread D Free 54

Acquiring and releasing locks Thread B Thread C Thread A Thread D Free 55

Acquiring and releasing locks Thread B Thread C Thread A Thread D Set 56

Acquiring and releasing locks Thread B Thread C Thread A Thread D Set 57

Acquiring and releasing locks Thread B Thread C Thread A Thread D Set 58

Acquiring and releasing locks Thread B Thread C Thread A Thread D Set 59

Acquiring and releasing locks Thread B Thread C Thread A Thread D Set 60

Acquiring and releasing locks Thread A Thread B Thread C Thread D Set 61

Acquiring and releasing locks Thread A Thread B Thread C Thread D Set 62

Acquiring and releasing locks Thread B Thread C Thread A Unlock Thread D Set 63

Acquiring and releasing locks Thread B Thread C Thread A Unlock Thread D Set 64

Acquiring and releasing locks Thread A Thread B Thread C Thread D Free 65

Acquiring and releasing locks Thread A Thread B Thread C Thread D Free 66

Acquiring and releasing locks Thread A Thread B Thread C Thread D Set 67

Acquiring and releasing locks Thread A Thread B Thread C Thread D Set 68

Acquiring and releasing locks Thread B Thread C Thread A Thread D Set 69

Mutex locks An abstract data type Used for synchronization and mutual exclusion The mutex is either: ed ( the lock is held ) Unlocked ( the lock is free ) 70

Mutex lock operations (mutex) Acquire the lock if it is free Otherwise wait until it can be acquired Unlock (mutex) Release the lock If there are waiting threads wake up one of them 71

How to use a mutex? Shared data: Mutex my; 1 repeat 2 (my); 3 critical section 4 Unlock(my); 5 remainder section 6 until FALSE 1 repeat 2 (my); 3 critical section 4 Unlock(my); 5 remainder section 6 until FALSE 72

How to implement a mutex? Both and Unlock must be atomic! Does a binary lock variable in memory work? Many computers have some limited hardware support for setting locks Atomic Test and Set instruction Atomic compare and swap operation Can be used to implement mutex locks 73

Test-and-set-lock instruction (TSL, tset) A lock is a single word variable with two values 0 = FALSE = not locked 1 = TRUE = locked Test-and-set does the following atomically: Get the (old) value Set the lock to TRUE Return the old value If the returned value was FALSE... Then you got the lock!!! If the returned value was TRUE... Then someone else has the lock (so try again later) 74

Test and set lock P1 FALSE 75

Test and set lock P1 FALSE FALSE = Available!! 76

Test and set lock P1 FALSE TRUE 77

Test and set lock P1 P2 P3 TRUE TRUE TRUE TRUE TRUE TRUE TRUE P4 78

Test and set lock P1 P2 P3 TRUE TRUE TRUE TRUE TRUE TRUE TRUE P4 79

Test and set lock P1 P2 P3 TRUE TRUE TRUE TRUE TRUE TRUE TRUE P4 80

Test and set lock P1 P2 P3 FALSE FALSE TRUE P4 81

Test and set lock P1 P2 P3 TRUE FALSE TRUE TRUE P4 82

Test and set lock P1 P2 P3 TRUE FALSE TRUE P4 83

Test and set lock P1 P2 P3 TRUE TRUE TRUE TRUE TRUE P4 84

Critical section entry code with TSL 1 repeat 2 while(tsl(lock)) 3 no-op; I 1 repeat 2 while(tsl(lock)) 3 no-op; J 4 critical section 4 critical section 5 = FALSE; 5 = FALSE; 6 remainder section 6 remainder section 7 until FALSE 7 until FALSE Guarantees that only one thread at a time will enter its critical section Note that processes are busy while waiting Spin locks 85

Busy waiting Also called polling or spinning The thread consumes CPU cycles to evaluate when the lock becomes free! Shortcoming on a single CPU system... A busy-waiting thread can prevent the lock holder from running & completing its critical section & releasing the lock! Why not block instead of busy wait? 86

Quiz What is the difference between a program and a process? Is the Operating System a program? Is the Operating System a process? Does it have a process control block? How is its state managed when it is not running? What is the difference between processes and threads? What tasks are involved in switching the CPU from one process to another? Why is it called a context switch? What tasks are involved in switching the CPU from one thread to another? Why are threads lightweight? 87