D u k e S y s t e m s Asynchrony, Concurrency, and Threads Jeff Chase Duke University.

Slides:



Advertisements
Similar presentations
Chapter 6: Process Synchronization
Advertisements

D u k e S y s t e m s Servers and Threads Jeff Chase Duke University.
Precept 3 COS 461. Concurrency is Useful Multi Processor/Core Multiple Inputs Don’t wait on slow devices.
Threads 1 CS502 Spring 2006 Threads CS-502 Spring 2006.
3.5 Interprocess Communication
Jonathan Walpole Computer Science Portland State University
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 3: Processes.
1 School of Computing Science Simon Fraser University CMPT 300: Operating Systems I Ch 4: Threads Dr. Mohamed Hefeeda.
CPS110: Implementing threads/locks on a uni-processor Landon Cox.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Scheduler Activations Jeff Chase. Threads in a Process Threads are useful at user-level – Parallelism, hide I/O latency, interactivity Option A (early.
Chapter 51 Threads Chapter 5. 2 Process Characteristics  Concept of Process has two facets.  A Process is: A Unit of resource ownership:  a virtual.
Operating Systems CSE 411 CPU Management Sept Lecture 11 Instructor: Bhuvan Urgaonkar.
Concurrency Recitation – 2/24 Nisarg Raval Slides by Prof. Landon Cox.
D u k e S y s t e m s Servers and Threads, Continued Jeff Chase Duke University.
Chapter 4: Threads. 4.2CSCI 380 Operating Systems Chapter 4: Threads Overview Multithreading Models Threading Issues Pthreads Windows XP Threads Linux.
1 Lecture 4: Threads Operating System Fall Contents Overview: Processes & Threads Benefits of Threads Thread State and Operations User Thread.
Threads, Thread management & Resource Management.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Threads and Concurrency. A First Look at Some Key Concepts kernel The software component that controls the hardware directly, and implements the core.
Operating Systems Lecture 2 Processes and Threads Adapted from Operating Systems Lecture Notes, Copyright 1997 Martin C. Rinard. Zhiqing Liu School of.
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
Copyright ©: University of Illinois CS 241 Staff1 Threads Systems Concepts.
CS333 Intro to Operating Systems Jonathan Walpole.
CSE 451: Operating Systems Section 5 Midterm review.
CPS110: Implementing threads Landon Cox. Recap and looking ahead Hardware OS Applications Where we’ve been Where we’re going.
Consider the program fragment below left. Assume that the program containing this fragment executes t1() and t2() on separate threads running on separate.
CSE 451: Operating Systems Winter 2015 Module 5 1 / 2 User-Level Threads & Scheduler Activations Mark Zbikowski 476 Allen Center.
Lecture 5: Threads process as a unit of scheduling and a unit of resource allocation processes vs. threads what to program with threads why use threads.
D u k e S y s t e m s More Synchronization featuring Producer/Consumer with Semaphores Jeff Chase Duke University.
1 Computer Systems II Introduction to Processes. 2 First Two Major Computer System Evolution Steps Led to the idea of multiprogramming (multiple concurrent.
Introduction to Operating Systems and Concurrency.
Discussion Week 2 TA: Kyle Dewey. Overview Concurrency Process level Thread level MIPS - switch.s Project #1.
Operating Systems CSE 411 CPU Management Sept Lecture 10 Instructor: Bhuvan Urgaonkar.
Department of Computer Science and Software Engineering
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
CSC 322 Operating Systems Concepts Lecture - 7: by Ahmed Mumtaz Mustehsan Special Thanks To: Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall,
Managing Processors Jeff Chase Duke University. The story so far: protected CPU mode user mode kernel mode kernel “top half” kernel “bottom half” (interrupt.
Processes and Threads MICROSOFT.  Process  Process Model  Process Creation  Process Termination  Process States  Implementation of Processes  Thread.
4.1 Introduction to Threads Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads.
Threads and Concurrency
D u k e S y s t e m s CPS 310 Threads and Concurrency: Topics Jeff Chase Duke University
Interrupts and Exception Handling. Execution We are quite aware of the Fetch, Execute process of the control unit of the CPU –Fetch and instruction as.
CPS110: Implementing threads on a uni-processor Landon Cox January 29, 2008.
Tutorial 2: Homework 1 and Project 1
Introduction to Operating Systems Concepts
Processes and threads.
Process Tables; Threads
CS 6560: Operating Systems Design
CS703 – Advanced Operating Systems
Scheduler activations
COMPSCI210 Recitation 12 Oct 2012 Vamsi Thummala
CS399 New Beginnings Jonathan Walpole.
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Threads and Synchronization
Process Tables; Threads
CS510 Operating System Foundations
Lecture Topics: 11/1 General Operating System Concepts Processes
Threads Chapter 4.
Background and Motivation
CSE 451: Operating Systems Autumn 2003 Lecture 7 Synchronization
CSE 451: Operating Systems Autumn 2005 Lecture 7 Synchronization
CSE 451: Operating Systems Winter 2003 Lecture 7 Synchronization
CSE 153 Design of Operating Systems Winter 19
CS333 Intro to Operating Systems
Foundations and Definitions
CS703 – Advanced Operating Systems
Threads CSE 2431: Introduction to Operating Systems
Presentation transcript:

D u k e S y s t e m s Asynchrony, Concurrency, and Threads Jeff Chase Duke University

Servers and concurrency Network servers receive concurrent requests. – Many clients send requests “at the same time”. Servers should handle those requests concurrently. – Don’t leave the server CPU idle if there is a request to work on. But how to do that with the classic Unix process model? – Unix had single-threaded processes and blocking syscalls. – If a process blocks it can’t do anything else until it wakes up. Shells face similar problems in tracking their children, which execute independently (asynchronously). Systems with GUIs also face them. What to do?

Handling a Web request Accept Client Connection Read HTTP Request Header Find File Send HTTP Response Header Read File Send Data may block waiting on disk I/O We want to be able to process requests concurrently. may block waiting on network

Concurrency/Asynchrony in Unix Some partial answers and options 1.Use multiple processes, e.g., one per server request. – Example: inetd and /etc/services – But how many processes? Aren’t they expensive? – We can only run one at a time per core anyway. 2.Introduce nonblocking (asynchronous) syscalls. – Example: wait*(WNOHANG). But you have to keep asking to know when a child exits. (polling) – What about starting asynchronous operations, like a read? How to know when it is done without blocking? – We need events to notify of completion. Maybe use signals? 3.Threads etc.

Web server (serial process)  Option 1: could handle requests serially  Easy to program, but painfully slow (why?) Client 1Client 2 WS R1 arrives Receive R1 R2 arrives Disk request 1a 1a completes R1 completes Receive R2

Web server (event-driven)  Option 2: use asynchronous I/O  Fast, but hard to program (why?) Client 1 Disk WS R1 arrives Receive R1 Disk request 1a 1a completes R1 completes Receive R2 Client 2 R2 arrives Finish 1a Start 1a

Web server (multiprogrammed)  Option 3: assign one thread per request  Where is each request’s state stored? Client 1Client 2WS1 R1 arrives Receive R1 R2 arrives Disk request 1a 1a completes R1 completes Receive R2 WS2

Event-driven programming Event-driven programming is a design pattern for a thread’s program. The thread receives and handles a sequence of typed events. – Handle one event at a time, in order. In its pure form the thread never blocks, except to get the next event. – Blocks only if no events to handle (idle). We can think of the program as a set of handler routines for the event types. – The thread upcalls the handler to dispatch or “handle” each event. events Dispatch events by invoking handlers (upcalls).

But what’s an event? A system can use an event-driven design pattern to handle any kind of asynchronous event. – arriving input (e.g., GUI clicks/swipes, requests to a server) – notify that an operation started earlier is complete – subscribe to events published by other processes – child stop/exit, “signals”, etc. System architects choose how to use event abstractions. – Kernel networking and I/O stacks are mostly event-driven (interrupts, callbacks, event queues, etc.), even if the system call APIs are blocking. – Example: Windows driver stack. – Real systems combine events and threading (for multicore).

Ideal event poll API Poll() 1.Delivers: returns exactly one event (message or notification), in its entirety, ready for service (dispatch). 2.Idles: Blocks iff there is no event ready for dispatch. 3.Consumes: returns each posted event at most once. 4.Combines: any of many kinds of events (a poll set) may be returned through a single call to poll. 5.Synchronizes: may be shared by multiple processes or threads (  handlers must be thread-safe as well).

Handling a Web request Accept Client Connection Read HTTP Request Header Find File Send HTTP Response Header Read File Send Data may block waiting on disk I/O Where should we use asynchronous events vs. blocking? may block waiting on network

Multi-programmed server: idealized Incoming request queue worker loop Handle one request, blocking as necessary. When request is complete, return to worker pool. Magic elastic worker pool Resize worker pool to match incoming request load: create/destroy workers as needed. dispatch idle workers Workers wait here for next request dispatch. Workers could be processes or threads.

Server structure in the real world The server structure discussion motivates threads, and illustrates the need for concurrency management. – We return later to performance impacts and effective I/O overlap. Theme: Unix systems fall short of the idealized model. – Thundering herd problem when multiple workers wake up and contend for an arriving request: one worker wins and consumes the request, the others go back to sleep – their work was wasted. Recent fix in Linux. – Separation of poll/select and accept in Unix syscall interface: multiple workers wake up when a socket has new data, but only one can accept the request: thundering herd again, requires an API change to fix it. – There is no easy way to manage an elastic worker pool. Real servers (e.g., Apache/MPM) incorporate lots of complexity to overcome these problems. We skip this topic.

Threads We now enter the topic of threads and concurrency control. – This will be a focus for several lectures. – We start by introducing more detail on thread management, and the problem of nondeterminism in concurrent execution schedules. Server structure discussion motivates threads, but there are other motivations. – Harnessing parallel computing power in the multicore era – Managing concurrent I/O streams – Organizing/structuring processing for user interface (UI) – Threading and concurrency management are fundamental to OS kernel implementation: processes/threads execute concurrently in the kernel address space for system calls and fault handling. The kernel is a multithreaded program. So let’s get to it….

Threads and the kernel Modern operating systems have multi- threaded processes. A program starts with one main thread, but once running it may create more threads. Threads may enter the kernel (e.g., syscall). Threads are known to the kernel and have separate kernel stacks, so they can block independently in the kernel. – Kernel has syscalls to create threads (e.g., Linux clone). Implementations vary. – This model applies to Linux, MacOS-X, Windows, Android, and pthreads or Java on those systems. data trap fault resume user mode user space kernel mode kernel space process threads VAS

Java threads: the basics class RunnableTask implements Runnable { public RunnableTask(…) { // save any arguments or input for the task (optional) } public void run() { // do task: your code here } … RunnableTask task = new RunnableTask(); Thread t1= new Thread(task, "thread1"); t1.start(); …

Java threads: the basics public void MyThread extends Thread { public void run() { // do task: your code here } … Thread t1 = new MyThread(); t1.start(); If you prefer, you may extend the Java Thread class.

Threads A thread is a stream of control. – defined by CPU register context (PC, SP, …) – Note: process “context” is thread context plus protected registers defining current VAS, e.g., ASID or “page table base register(s)”. – Generally “context” is the register values and referenced memory state (stack, page tables) Multiple threads can execute independently: – They can run in parallel on multiple cores... physical concurrency – …or arbitrarily interleaved on a single core. logical concurrency – Each thread must have its own stack.

A process can have multiple threads volatile int counter = 0; int loops; void *worker(void *arg) { int i; for (i = 0; i < loops; i++) { counter++; } pthread_exit(NULL); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: threads \n"); exit(1); } loops = atoi(argv[1]); pthread_t p1, p2; printf("Initial value : %d\n", counter); pthread_create(&p1, NULL, worker, NULL); pthread_create(&p2, NULL, worker, NULL); pthread_join(p1, NULL); pthread_join(p2, NULL); printf("Final value : %d\n", counter); return 0; } data Much more on this later!

Two threads sharing a CPU reality concept context switch

CPU Scheduling 101 The OS scheduler makes a sequence of “moves”. – Next move: if a CPU core is idle, pick a ready thread from the ready pool and dispatch it (run it). – Scheduler’s choice is “nondeterministic” – Scheduler and machine determine the interleaving of execution (a schedule). Wakeup GetNextToRun SWITCH() ready pool blocked threads If timer expires, or wait/yield/terminate

Reading Between the Lines of C load add store load add store Two executions of this code, so: x is incremented by two. ✔ loadx, R2; load global variable x addR2, 1, R2; increment: x = x + 1 storeR2, x; store global variable x Two threads execute this code section. x is a shared variable.

Interleaving matters loadx, R2; load global variable x addR2, 1, R2; increment: x = x + 1 storeR2, x; store global variable x load add store load add store In this schedule, x is incremented only once: last writer wins. The program breaks under this schedule. This bug is a race. Two threads execute this code section. x is a shared variable. X

Non-determinism and ordering Time Thread A Thread B Thread C Global ordering Why do we care about the global ordering? Might have dependencies between events Different orderings can produce different results Why is this ordering unpredictable? Can’t predict how fast processors will run

Non-determinism example  y=10;  Thread A: x = y+1;  Thread B: y = y*2;  Possible results?  A goes first: x = 11 and y = 20  B goes first: y = 20 and x = 21  Variable y is shared between threads.

Another example  Two threads (A and B)  A tries to increment i  B tries to decrement i Thread A: i = 0; while (i < 10){ i++; } print “A done.” Thread B: i = 0; while (i > -10){ i--; } print “B done.”

Example continued  Who wins?  Does someone have to win? Thread A: i = 0; while (i < 10){ i++; } print “A done.” Thread B: i = 0; while (i > -10){ i--; } print “B done.”

Concurrency control Each thread executes a sequence of instructions, but their sequences may be arbitrarily interleaved. – E.g., from the point of view of loads/stores on memory. Each possible execution order is a schedule. It is the program’s responsibility to exclude schedules that lead to incorrect behavior. It is called synchronization or concurrency control. The scheduler (and the machine) select the execution order of threads

Resource Trajectory Graphs Resource trajectory graphs (RTG) depict the “random walk” through the space of possible program states. RTG for N threads is N-dimensional. Thread i advances along axis i. Each point represents one state in the set of all possible system states. Cross-product of the possible states of all threads in the system SnSn SoSo SmSm

Resource Trajectory Graphs This RTG depicts a schedule within the space of possible schedules for a simple program of two threads sharing one core. Blue advances along the y-axis. Purple advances along the x-axis. The scheduler chooses the path (schedule, event order, or interleaving). The diagonal is an idealized parallel execution (two cores). Every schedule starts here. EXIT Every schedule ends here. context switch From the point of view of the program, the chosen path is nondeterministic.

This is not a game But we can think of it as a game. 1.You write your program. 2.The game begins when you submit your program to your adversary: the scheduler. 3.The scheduler chooses all the moves while you watch. 4.Your program may constrain the set of legal moves. 5.The scheduler searches for a legal schedule that breaks your program. 6.If it succeeds, then you lose (your program has a race). 7.You win by not losing. x=x+1 

The need for mutual exclusion The program may fail if the schedule enters the grey box (i.e., if two threads execute the critical section concurrently). The two threads must not both operate on the shared global x “at the same time”. x=x+1 x=??? 

A Lock or Mutex Locks are the basic tools to enforce mutual exclusion in conflicting critical sections. A lock is a special data item in memory. API methods: Acquire and Release. Also called Lock() and Unlock(). Threads pair calls to Acquire and Release. Acquire upon entering a critical section. Release upon leaving a critical section. Between Acquire/Release, the thread holds the lock. Acquire does not pass until any previous holder releases. Waiting locks can spin (a spinlock) or block (a mutex). A A R R

Definition of a lock (mutex) Acquire + release ops on L are strictly paired. – After acquire completes, the caller holds (owns) the lock L until the matching release. Acquire + release pairs on each L are ordered. – Total order: each lock L has at most one holder at any given time. – That property is mutual exclusion; L is a mutex.

Portrait of a Lock in Motion A A R R The program may fail if it enters the grey box. A lock (mutex) prevents the schedule from ever entering the grey box, ever: both threads would have to hold the same lock at the same time, and locks don’t allow that. x=x+1 x=??? 

Handing off a lock First I go. Then you go. release acquire Handoff The nth release, followed by the (n+1)th acquire serialized (one after the other)

Example: event/request queue Incoming event queue worker loop Handle one event, blocking as necessary. When handler is complete, return to worker pool. We can use a mutex to protect a shared event queue. “Lock it down.” dispatch threads waiting for event But how will worker threads wait on an empty queue? How to wait for arrival of the next event? We need suitable primitives to wait (block) for a condition and notify when it is satisfied.

New Problem: Ping-Pong void PingPong() { while(not done) { … if (blue) switch to purple; if (purple) switch to blue; }

Ping-Pong with Mutexes? void PingPong() { while(not done) { Mx->Acquire(); … Mx->Release(); } ???

Mutexes don’t work for ping-pong

Condition variables A condition variable (CV) is an object with an API. – wait: block until the condition becomes true Not to be confused with Unix wait* system call – signal (also called notify): signal that the condition is true Wake up one waiter. Every CV is bound to exactly one mutex, which is necessary for safe use of the CV. – “holding the mutex”  “in the monitor” A mutex may have any number of CVs bound to it. CVs also define a broadcast (notifyAll) primitive. – Signal all waiters.

Ping-Pong using a condition variable void PingPong() { mx->Acquire(); while(not done) { … cv->Signal(); cv->Wait(); } mx->Release(); }

Ping-Pong using a condition variable wait signal wait signal wait signal

Ping-Pong using a condition variable wait notify (signal) wait signal (notify) wait signal public synchronized void PingPong() { while(true) { notify(); wait(); } Interchangeable lingo synchronized == mutex == lock monitor == mutex+CV notify == signal Suppose blue gets the mutex first: its notify is a no-op. waiting for signal cannot acquire mutex

Mutual exclusion in Java Mutexes are built in to every Java object. – no separate classes Every Java object is/has a monitor. – At most one thread may “own” a monitor at any given time. A thread becomes owner of an object’s monitor by – executing an object method declared as synchronized – executing a block that is synchronized on the object public void increment() { synchronized(this) { x = x + 1; } public synchronized void increment() { x = x + 1; }

Java synchronization public class Object { void notify(); /* signal */ void notifyAll(); /* broadcast */ void wait(); void wait(long timeout); } public class PingPong extends Object { public synchronized void PingPong() { while(true) { notify(); wait(); } Every Java object has a monitor and condition variable built in. There is no separate mutex class or CV class. A thread must own an object’s monitor (“synchronized”) to call wait/notify, else the method raises an IllegalMonitorStateException. Wait(*) waits until the timeout elapses or another thread notifies.

Debugging non-determinism  Requires worst-case reasoning  Eliminate all ways for program to break  Debugging is hard  Can’t test all possible interleavings  Bugs may only happen sometimes  Heisenbug  Re-running program may make the bug disappear  Doesn’t mean it isn’t still there!

Note The following slides weren’t discussed in class. They add more detail to the class discussion of thread systems, by explaining the distinction between “kernel-based” and “user-level” (“green”) threads. This material is for your interest. It won’t be tested unless and until we return to it.

Portrait of a thread machine state name/status etc 0xdeadbeef Stack low high Thread operations a rough sketch: t = create(); t.start(proc, arg); t.alert(); (optional) result = t.join(); Self operations a rough sketch: exit(result); t = self(); setdata(ptr); ptr = selfdata(); alertwait(); (optional) Details vary.

A thread: closer look User TCB 0xdeadbeef user stack Kernel TCB kernel stack saved context thread library threads, mutexes, condition variables… kernel thread support raw “vessels”, e.g., Linux CLONE_THREAD+”futex” thread API e.g., pthreads or Java threads kernel interface for thread libs (not for users) 1-to-1 mapping of user threads to dedicated kernel supported “vessels” Threads can enter the kernel (fault or trap) and block, so they need a k-stack. (Some older user-level “green” thread libraries may multiplex multiple user threads over each “vessel”.) PG-13

Kernel-based vs. user-level threads Take 2 A thread system schedules threads over a pool of “logical cores” or “vessels” for threads to run in. The kernel provides the vessels: they are either classic processes or “lightweight” processes, e.g., via CLONE_THREAD. Kernel scheduler schedules/multiplexes vessels on core slots: – Select at most one vessel to occupy each core slot at any given time. – Each vessel occupies at most one core slot at any given time. – Vessels have k-stacks and can block independently in the kernel. A “kernel-based thread system” maintains a stable 1-1 mapping of threads to dedicated vessels. – There is no user-level thread scheduler, since the mapping is stable. – For simplicity we just call each (thread, vessel) pair a “thread”. A thread library can always choose to multiplex N threads over M vessels. It used to be necessary but it’s not anymore. It causes problems with I/O because the threads cannot block independently in the kernel and the kernel does not know about the threads. There might still be performance-related reasons to do it in some scenarios but we IGNORE THAT CASE from now on.

Thread models illustrated data user-level thread readyList data while(1) { t = get next ready thread; scheduler->Run(t); } Optional add on: a library that multiplexes N user-level threads over M kernel thread vessels, N > M. 1-to-1 mapping of user threads to dedicated kernel supported “vessels” Thread/vessels block via kernel syscalls. They block in the kernel, not in user space. Each has a kernel stack, so they can block independently. Syscall interface for “vessels” as a foundation for thread API libraries. Might call the vessels “threads” or “lightweight processes”. Kernel scheduler (not library) decides which thread/vessel to run next.