– 1 – 15-213, F’02 Traditional View of a Process Process = process context + code, data, and stack shared libraries run-time heap 0 read/write data Program.

Slides:



Advertisements
Similar presentations
Carnegie Mellon 1 Concurrent Programming / : Introduction to Computer Systems 23 rd Lecture, Nov. 15, 2012 Instructors: Dave O’Hallaron, Greg.
Advertisements

Programming with Threads Topics Threads Shared variables The need for synchronization Synchronizing with semaphores Thread safety and reentrancy Races.
CONDITION VARIABLE. Announcements  Quiz  Getting the big picture  Programming assignments  Cooperation  Lecture is cut 20 mins short for Quiz and.
Programming with Threads November 26, 2003 Topics Shared variables The need for synchronization Synchronizing with semaphores Thread safety and reentrancy.
Carnegie Mellon 1 Synchronization: Basics : Introduction to Computer Systems 23 rd Lecture, Nov. 16, 2010 Instructors: Randy Bryant and Dave O’Hallaron.
Lecture 4: Concurrency and Threads CS 170 T Yang, 2015 Chapter 4 of AD textbook.
Synchronization April 29, 2008 Topics Shared variables The need for synchronization Synchronizing with semaphores Thread safety and reentrancy Races and.
Concurrent HTTP Proxy with Caching Ashwin Bharambe Monday, Dec 4, 2006.
Programming with Threads Topics Threads Shared variables The need for synchronization Synchronizing with semaphores Thread safety and reentrancy Races.
Carnegie Mellon 1 Synchronization: Basics / : Introduction to Computer Systems 23 rd Lecture, Jul 21, 2015 Instructors: nwf and Greg Kesden.
Programming with Threads April 30, 2002 Topics Shared variables The need for synchronization Synchronizing with semaphores Synchronizing with mutex and.
Carnegie Mellon /18-243: Introduction to Computer Systems Instructors: Bill Nace and Gregory Kesden (c) All Rights Reserved. All work.
1 Concurrent Programming Andrew Case Slides adapted from Mohamed Zahran, Jinyang Li, Clark Barrett, Randy Bryant and Dave O’Hallaron.
ECE 297 Concurrent Servers Process, fork & threads ECE 297.
1 Concurrent Programming. 2 Outline Semaphores for Shared Resources –Producer-consumer problem –Readers-writers problem Example –Concurrent server based.
1 Concurrent Programming. 2 Outline Concurrent programming –Processes –Threads Suggested reading: –12.1, 12.3.
Carnegie Mellon 1 Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition Concurrent Programming : Introduction to Computer.
CS333 Intro to Operating Systems Jonathan Walpole.
Week 16 (April 25 th ) Outline Thread Synchronization Lab 7: part 2 & 3 TA evaluation form Reminders Lab 7: due this Thursday Final review session Final.
Threads CSCE Thread Motivation Processes are expensive to create. Context switch between processes is expensive Communication between processes.
PROCESS AND THREADS. Three ways for supporting concurrency with socket programming  I/O multiplexing  Select  Epoll: man epoll  Libevent 
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
Carnegie Mellon Introduction to Computer Systems /18-243, fall nd Lecture, Nov. 17 Instructors: Roger B. Dannenberg and Greg Ganger.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Programming with Threads Topics Threads Shared variables The need for synchronization Synchronizing with semaphores Thread safety and reentrancy Races.
Thread S04, Recitation, Section A Thread Memory Model Thread Interfaces (System Calls) Thread Safety (Pitfalls of Using Thread) Racing Semaphore.
Carnegie Mellon 1 Concurrent Programming / : Introduction to Computer Systems 22 nd Lecture, Nov. 11, 2014 Instructors: Greg Ganger, Greg.
Concurrency I: Threads Nov 9, 2000 Topics Thread concept Posix threads (Pthreads) interface Linux Pthreads implementation Concurrent execution Sharing.
Concurrency Threads Synchronization Thread-safety of Library Functions Anubhav Gupta Dec. 2, 2002 Outline.
Carnegie Mellon Recitation 11: ProxyLab Fall 2009 November 16, 2009 Including Material from Previous Semesters' Recitations.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
December 1, 2006©2006 Craig Zilles1 Threads & Atomic Operations in Hardware  Previously, we introduced multi-core parallelism & cache coherence —Today.
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
Synchronization /18-243: Introduction to Computer Systems
Instructor: Haryadi Gunawi
Instructors: Gregory Kesden and Markus Püschel
Threads Synchronization Thread-safety of Library Functions
Synchronization: Basics
Instructors: Randal E. Bryant and David R. O’Hallaron
Programming with Threads
Programming with Threads
Threads in C Caryl Rahn.
Threads Threads.
CS399 New Beginnings Jonathan Walpole.
Concurrent Programming November 13, 2008
Concurrency I: Threads April 10, 2001
Concurrent Servers Topics Limitations of iterative servers
Instructor: Randy Bryant
Programming with Threads
Concurrent Programming
Programming with Threads
Programming with Threads Dec 6, 2001
Programming with Threads Dec 5, 2002
CS703 - Advanced Operating Systems
Concurrent Programming : Introduction to Computer Systems 23rd Lecture, Nov. 13, 2018
Concurrent Programming CSCI 380: Operating Systems
Synchronization: Basics CSCI 380: Operating Systems
Realizing Concurrency using Posix Threads (pthreads)
Programming with Threads
Programming with Threads
Synchronization: Advanced CSCI 380: Operating Systems
Concurrent Programming November 13, 2008
Programming with Threads
Instructor: Brian Railing
Lecture 19: Threads CS April 3, 2019.
Instructor: Brian Railing
Programming with Threads
Threads CSE 2431: Introduction to Operating Systems
Concurrent Programming
Presentation transcript:

– 1 – , F’02 Traditional View of a Process Process = process context + code, data, and stack shared libraries run-time heap 0 read/write data Program context: Data registers Condition codes Stack pointer (SP) Program counter (PC) Kernel context: VM structures Descriptor table brk pointer Code, data, and stack read-only code/data stack SP PC brk Process context

– 2 – , F’02 Alternate View of a Process Process = thread + code, data, and kernel context shared libraries run-time heap 0 read/write data Thread context: Data registers Condition codes Stack pointer (SP) Program counter (PC) Code and Data read-only code/data stack SP PC brk Thread (main thread) Kernel context: VM structures Descriptor table brk pointer

– 3 – , F’02 A Process With Multiple Threads Multiple threads can be associated with a process Each thread has its own logical control flow (sequence of PC values) Each thread shares the same code, data, and kernel context Each thread has its own thread id (TID) shared libraries run-time heap 0 read/write data Thread 1 context: Data registers Condition codes SP1 PC1 Shared code and data read-only code/data stack 1 Thread 1 (main thread) Kernel context: VM structures Descriptor table brk pointer Thread 2 context: Data registers Condition codes SP2 PC2 stack 2 Thread 2 (peer thread)

– 4 – , F’02 Logical View of Threads Threads associated with a process form a pool of peers. Unlike processes which form a tree hierarchy P0 P1 sh foo bar T1 Process hierarchy Threads associated with process foo T2 T4 T5 T3 shared code, data and kernel context

– 5 – , F’02 Concurrent Thread Execution Two threads run concurrently (are concurrent) if their logical flows overlap in time. Otherwise, they are sequential. Examples: Concurrent: A & B, A&C Sequential: B & C Time Thread AThread BThread C

– 6 – , F’02 Threads vs. Processes How threads and processes are similar Each has its own logical control flow. Each can run concurrently. Each is context switched. How threads and processes are different Threads share code and data, processes (typically) do not. Threads are somewhat less expensive than processes. Process control (creating and reaping) is twice as expensive as thread control. Linux/Pentium III numbers: »~20K cycles to create and reap a process. »~10K cycles to create and reap a thread.

– 7 – , F’02 The Pthreads "hello, world" Program /* * hello.c - Pthreads "hello, world" program */ #include "csapp.h" void *thread(void *vargp); int main() { pthread_t tid; Pthread_create(&tid, NULL, thread, NULL); Pthread_join(tid, NULL); exit(0); } /* thread routine */ void *thread(void *vargp) { printf("Hello, world!\n"); return NULL; } Thread attributes (usually NULL) Thread arguments (void *p) return value (void **p)

– 8 – , F’02 Execution of Threaded“hello, world” main thread peer thread return NULL; main thread waits for peer thread to terminate exit() terminates main thread and any peer threads call Pthread_create() call Pthread_join() Pthread_join() returns printf() (peer thread terminates) Pthread_create() returns

– 9 – , F’02 Pros and Cons of Thread-Based Designs + Easy to share data structures between threads e.g., logging information, file cache. + Threads are more efficient than processes. --- Unintentional sharing can introduce subtle and hard- to-reproduce errors! The ease with which data can be shared is both the greatest strength and the greatest weakness of threads.

– 10 – , F’02 Shared Variables in Threaded C Programs Question: Which variables in a threaded C program are shared variables? The answer is not as simple as “global variables are shared” and “stack variables are private”. Requires answers to the following questions: What is the memory model for threads? How are variables mapped to memory instances? How many threads reference each of these instances?

– 11 – , F’02 Threads Memory Model Conceptual model: Each thread runs in the context of a process. Each thread has its own separate thread context. Thread ID, stack, stack pointer, program counter, condition codes, and general purpose registers. All threads share the remaining process context. Code, data, heap, and shared library segments of the process virtual address space. Open files and installed handlers Operationally, this model is not strictly enforced: While register values are truly separate and protected.... Any thread can read and write the stack of any other thread. Mismatch between the conceptual and operation model is a source of confusion and errors.

– 12 – , F’02 Thread Safety Functions called from a thread must be thread-safe. We identify four (non-disjoint) classes of thread-unsafe functions: Class 1: Failing to protect shared variables. Class 2: Relying on persistent state across invocations. Class 3: Returning a pointer to a static variable. Class 4: Calling thread-unsafe functions.

– 13 – , F’02 Thread-Unsafe Functions Class 1: Failing to protect shared variables. Fix: Use semaphore operations. Issue: Synchronization operations will slow down code.

– 14 – , F’02 Thread-Unsafe Functions (cont) Class 2: Relying on persistent state across multiple function invocations. Random number generator relies on static state Fix: Rewrite function so that caller passes in all necessary state. /* rand - return pseudo-random integer on */ int rand(void) { static unsigned int next = 1; next = next* ; return (unsigned int)(next/65536) % 32768; } /* srand - set seed for rand() */ void srand(unsigned int seed) { next = seed; }

– 15 – , F’02 Thread-Unsafe Functions (cont) Class 3: Returning a ptr to a static variable. Fixes: 1. Rewrite code so caller passes pointer to struct. »Issue: Requires changes in caller and callee. 2. Lock-and-copy »Issue: Requires only simple changes in caller (and none in callee) »However, caller must free memory. hostp = Malloc(...)); gethostbyname_r(name, hostp); struct hostent *gethostbyname(char name) { static struct hostent h; return &h; } struct hostent *gethostbyname_ts(char *p) { struct hostent *q = Malloc(...); P(&mutex); /* lock */ p = gethostbyname(name); *q = *p; /* copy */ V(&mutex); return q; }

– 16 – , F’02 Thread-Unsafe Functions Class 4: Calling thread-unsafe functions. Calling one thread-unsafe function makes an entire function thread-unsafe. Fix: Modify the function so it calls only thread-safe functions

– 17 – , F’02 Reentrant Functions A function is reentrant iff it accesses NO shared variables when called from multiple threads. Reentrant functions are a proper subset of the set of thread-safe functions. NOTE: The fixes to Class 2 and 3 thread-unsafe functions require modifying the function to make it reentrant. Reentrant functions All functions Thread-unsafe functions Thread-safe functions

– 18 – , F’02 Thread-Safe Library Functions All functions in the Standard C Library (at the back of your K&R text) are thread-safe. Examples: malloc, free, printf, scanf Most Unix system calls are thread-safe, with a few exceptions: Thread-unsafe functionClassReentrant version asctime 3asctime_r ctime 3ctime_r gethostbyaddr 3gethostbyaddr_r gethostbyname 3gethostbyname_r inet_ntoa 3(none) localtime 3localtime_r rand 2rand_r

– 19 – , F’02 Races A race occurs when the correctness of the program depends on one thread reaching point x before another thread reaches point y. /* a threaded program with a race */ int main() { pthread_t tid[N]; int i; for (i = 0; i < N; i++) Pthread_create(&tid[i], NULL, thread, &i); for (i = 0; i < N; i++) Pthread_join(tid[i], NULL); exit(0); } /* thread routine */ void *thread(void *vargp) { int myid = *((int *)vargp); printf("Hello from thread %d\n", myid); return NULL; }

– 20 – , F’02 deadlock region Deadlock P(s)V(s) V(t) Thread 1 Thread 2 Initially, s=t=1 P(t) V(t) forbidden region for s forbidden region for t P(s) V(s) deadlock state Locking introduces the potential for deadlock: waiting for a condition that will never be true. Any trajectory that enters the deadlock region will eventually reach the deadlock state, waiting for either s or t to become nonzero. Other trajectories luck out and skirt the deadlock region. Unfortunate fact: deadlock is often non-deterministic.

– 21 – , F’02 Threads Summary Threads provide another mechanism for writing concurrent programs. Threads are growing in popularity Somewhat cheaper than processes. Easy to share data between threads. However, the ease of sharing has a cost: Easy to introduce subtle synchronization errors. Tread carefully with threads! For more info: D. Butenhof, “Programming with Posix Threads”, Addison- Wesley, 1997.