Concurrency and Threads

Similar documents
Concurrency: Threads. CSE 333 Autumn 2018

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CMPSC 311- Introduction to Systems Programming Module: Concurrency

Server-side Programming

CMPSC 311- Introduction to Systems Programming Module: Concurrency

LSN 13 Linux Concurrency Mechanisms

Introduction to PThreads and Basic Synchronization

CSE 333 Lecture fork, pthread_create, select

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

Thread and Synchronization

C++ Inheritance I. CSE 333 Spring Instructor: Justin Hsia

THREADS. Jo, Heeseung

CSE 333 Section 9 - pthreads

Introduction to Concurrency

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

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

C++ Constructor Insanity

Computer Systems Laboratory Sungkyunkwan University

CS 3305 Intro to Threads. Lecture 6

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

The Heap and Structs. CSE 333 Spring Instructor: Justin Hsia

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

Threads. Threads (continued)

POSIX PTHREADS PROGRAMMING

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

High Performance Computing Course Notes Shared Memory Parallel Programming

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

Concurrency, Thread. Dongkun Shin, SKKU

Memory and Arrays. CSE 333 Spring Instructor: Justin Hsia

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

C++ Inheritance II, Casting

CSE 333 SECTION 9. Threads

Threads and Too Much Milk! CS439: Principles of Computer Systems January 31, 2018

Introduction to pthreads

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

Computer Science 162, Fall 2014 David Culler University of California, Berkeley Midterm 1 September 29, 2014

Threads and Too Much Milk! CS439: Principles of Computer Systems February 6, 2019

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

Programming with Shared Memory. Nguyễn Quang Hùng

Threads (light weight processes) Chester Rebeiro IIT Madras

Concurrent Server Design Multiple- vs. Single-Thread

ENCM 501 Winter 2019 Assignment 9

pthreads CS449 Fall 2017

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

Operating systems fundamentals - B06

POSIX Threads. HUJI Spring 2011

Synchronization. CS61, Lecture 18. Prof. Stephen Chong November 3, 2011

CS510 Operating System Foundations. Jonathan Walpole

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

POSIX Threads. Paolo Burgio

CSC Systems Programming Fall Lecture - XIV Concurrent Programming. Tevfik Ko!ar. Louisiana State University. November 2nd, 2010

Threads. studykorner.org

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

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

CS533 Concepts of Operating Systems. Jonathan Walpole

Threads. lightweight processes

CSE 374 Programming Concepts & Tools

CS333 Intro to Operating Systems. Jonathan Walpole

CS 326: Operating Systems. Process Execution. Lecture 5

User Space Multithreading. Computer Science, University of Warwick

Concurrency. Johan Montelius KTH

High Performance Computing Lecture 21. Matthew Jacob Indian Institute of Science

Multithreading Programming II

real time operating systems course

CSE 153 Design of Operating Systems Fall 2018

Lecture 19: Shared Memory & Synchronization

Roadmap. Concurrent Programming. Concurrent Programming. Communication Between Tasks. Motivation. Tevfik Ko!ar

Network Programming TDC 561

CSC Systems Programming Fall Lecture - XVIII Concurrent Programming. Tevfik Ko!ar. Louisiana State University. November 11 th, 2008

ANSI/IEEE POSIX Standard Thread management

CS Lecture 3! Threads! George Mason University! Spring 2010!

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

CSE 153 Design of Operating Systems

Threads. Jo, Heeseung

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

POSIX Threads: a first step toward parallel programming. George Bosilca

PThreads in a Nutshell

CSE 333 Final Exam June 8, 2016 Sample Solution

Threads Tuesday, September 28, :37 AM

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

CS510 Operating System Foundations. Jonathan Walpole

Introduction to Concurrency

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

Threads need to synchronize their activities to effectively interact. This includes:

TCSS 422: OPERATING SYSTEMS

CS 261 Fall Mike Lam, Professor. Threads

Threads. Jo, Heeseung

Chapter 4 Concurrent Programming

Roadmap. Concurrent Programming. Concurrent Programming. Motivation. Why Threads? Tevfik Ko!ar. CSC Systems Programming Fall 2010

Parallel Programming with Threads

Review: Easy Piece 1

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

Thread Concept. Thread. No. 3. Multiple single-threaded Process. One single-threaded Process. Process vs. Thread. One multi-threaded Process

Concurrent Programming

Processes and Threads

Concurrency, Mutual Exclusion and Synchronization C H A P T E R 5

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

Lecture #7: Implementing Mutual Exclusion

Synchronization Primitives

POSIX Threads: a first step toward parallel programming. George Bosilca

Transcription:

Concurrency and Threads CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon Huang Wei Lin

Administrivia Exercise 17 released yesterday, due Wednesday (5/30) Concurrency via pthreads hw4 due next Thursday (5/31) Submissions accepted until Sunday (6/3) Final is Tuesday (6/5), 12:30-2:20 pm, KNE 120 Review Session: Sunday (6/3), 4-6:30 pm, EEB 125 Two double-sided, handwritten sheets of notes allowed Topic list and past finals on Exams page on website 2

Some Common hw4 Bugs Your server works, but is really, really slow Check the 2 nd argument to the QueryProcessor constructor Funny things happen after the first request Make sure you re not destroying the HTTPConnection object too early (e.g. falling out of scope in a while loop) Server crashes on a blank request Make sure that you handle the case that read() (or WrappedRead()) returns 0 3

Review Servers should be concurrent Sequential query processing has terrible performance, as client interactions block for arbitrarily long periods of time Different ways to process multiple queries simultaneously: Issue multiple I/O requests simultaneously Overlap the I/O of one request with computation of another Utilize multiple CPUs or cores 4

Outline searchserver Sequential Concurrent via dispatching threads pthread_create() Concurrent via forking processes fork() Reference: CSPP, Chapter 12 5

Sequential Pseudocode: listen_fd = Listen(port); while (1) { client_fd = accept(listen_fd); buf = read(client_fd); resp = ProcessQuery(buf); write(client_fd, resp); close(client_fd); } See searchserver_sequential/ 6

Why Sequential? Advantages: Super simple to build/write Disadvantages: Incredibly poor performance One slow client will cause all others to block Poor utilization of resources (CPU, network, disk) 7

Threads Threads are like lightweight processes They execute concurrently like processes Multiple threads can run simultaneously on multiple CPUs/cores Unlike processes, threads cohabitate the same address space Threads within a process see the same heap and globals and can communicate with each other through variables and memory Each thread has its own stack 8

Threads and Address Spaces OS kernel [protected] Before creating a thread SP parent Stack parent Shared Libraries One thread of execution running in the address space That main thread invokes a function to create a new thread Typically pthread_create() PC parent Heap (malloc/free) Read/Write Segment.data,.bss Read-Only Segment.text,.rodata 9

Threads and Address Spaces SP parent SP child PC child PC parent OS kernel [protected] Stack parent Stack child Shared Libraries Heap (malloc/free) Read/Write Segment.data,.bss Read-Only Segment.text,.rodata After creating a thread Two threads of execution running in the address space Extra stack created Child thread maintains separate values for its SP and PC Both threads share the other segments They can cooperatively modify shared data 10

pthreads Threads int pthread_create( pthread_t* thread, const pthread_attr_t* attr, void* (*start_routine)(void*), void* arg); int pthread_detach(pthread_t thread); int pthread_join(pthread_t thread, void** retval); 11

Thread Example See thread_example.cc Remember process graphs? They work for threads, too! 12

Concurrency with Threads A single process handles all of the connections, but a parent thread dispatches a new thread to handle each connection The child thread handles the new connection and then exits when the connection terminates 13

Multithreaded Server client accept() server 14

Multithreaded Server client pthread_create() server 15

Multithreaded Server client accept() server 16

Multithreaded Server client client pthread_create() server 17

Multithreaded Server client client client client shared data structures client client server 18

Concurrent Via Threads See searchserver_threads/ Notes: When calling pthread_create(), start_routine points to a function that takes only one argument (a void*) To pass into the thread, create a struct to bundle the necessary data How do you properly handle memory management? Who allocates and deallocates memory? How long do you want memory to stick around? 19

Why Concurrent Threads? Advantages: Code is still straightforward Can write threaded code like sequential, but be careful with dispatch Concurrent execution with good CPU and network utilization Some overhead, but less than processes Shared-memory communication is possible Disadvantages: Synchronization is complicated Shared fate within a process One rogue thread can hurt you badly 20

Threads and Data Races What happens if two threads try to mutate the same data structure? They might interfere in painful, non-obvious ways, depending on the specifics of the data structure Example: two threads try to push an item onto the head of the linked list at the same time Could get correct answer Could get different ordering of items Could break the data structure! 21

Data Race Example If your fridge has no milk, then go out and buy some more if (!milk) { buy milk If you live alone: } If you live with a roommate:!! 22

Data Race Example Idea: leave a note! Does this fix the problem? Vote at http://pollev.com/justinh A. Yes, problem fixed B. No, could end up with no milk C. No, could still buy multiple milk D. We re lost if (!note) { if (!milk) { leave note buy milk remove note } } 23

Synchronization Synchronization is the act of preventing two (or more) concurrently running threads from interfering with each other when operating on shared data Need some mechanism to coordinate the threads Let me go first, then you can go Many different coordination mechanisms have been invented (CSE451) Goals of synchronization: Liveness ability to execute in a timely manner Safety avoid unintended interactions with shared data structures 24

Lock Synchronization Use a Lock to grant access to a critical section so that only one thread can operate there at a time Executed in an uninterruptible (i.e. atomic) manner Lock Acquire Wait until the lock is free, then take it Lock Release Pseudocode: // non-critical code lock.acquire(); // critical section lock.release(); loop/idle if locked // non-critical code Release the lock If other threads are waiting, wake exactly one up to pass lock to 25

Data Race Example With Locks What if we use a lock on the refrigerator? Probably overkill what if roommate wanted to get eggs? fridge.lock() if (!milk) { buy milk } fridge.unlock() For performance reasons, only put what is necessary in the critical section Only lock the milk milk_lock.lock() if (!milk) { buy milk } milk_lock.unlock() 26

pthreads and Locks Another term for a lock is a mutex ( mutual exclusion ) pthreads (#include <pthread.h>) defines datatype pthread_mutex_t pthread_mutex_init() int pthread_mutex_init(pthread_mutex_t* mutex, const pthread_mutexattr_t* attr); Initializes a mutex with specified attributes pthread_mutex_lock() int pthread_mutex_lock(pthread_mutex_t* mutex); Acquire the lock blocks if already locked pthread_mutex_unlock() int pthread_mutex_unlock(pthread_mutex_t* mutex); Releases the lock 27

C++11 Threads C++11 added threads and concurrency to its libraries <thread> thread objects <mutex> locks to handle critical sections <condition_variable> used to block objects until notified to resume <atomic> indivisible, atomic operations <future> asynchronous access to data These might be built on top of <pthread.h>, but also might not be Definitely use in C++11 code, but pthreads will be around for a long, long time Use pthreads in Exercise 17 28