COMP 3430 Robert Guderian

Size: px
Start display at page:

Download "COMP 3430 Robert Guderian"

Transcription

1 Operating Systems COMP 3430 Robert Guderian file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 1/58 1

2 Threads Last week: Processes This week: Lesser processes! file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 2/58 2

3 Relevant chapters Chapter 26 file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 3/58 3

4 Why threads Wrangling processes is complicated (sooooooooon) Can we do more than 1 task at a time with minimal overhead? file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 4/58 4

5 Caveat The two (or more) tasks should be highly related! They should be components of solving the same problem. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 5/58 5

6 Threads "Lightweight processes" Processes can have 1 or more thread. Linux, by default, has 1 thread. We can multi-thread a process - parallelism! file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 6/58 6

7 Threads vs Processes Processes: 1 PCB, image each Threads: Share PCB, image, memory file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 7/58 7

8 What it looks like in memory Each thread recieves its own stack Stack <-> state! Really, they'd all need their own stack... one return shouldn't return all the things file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 8/58 8

9 What it looks like, visually file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 9/58 9

10 Inexpesive to make Threads are incredibly cheap to make no new PCB needed no new memory needs to be allocated The OS sees these as on big process file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 10/58 10

11 But... Nothing is free: Sharing memory Threads share the heap + text, but not kindly We need to manage shared resources between threads file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 11/58 11

12 Thread dangers OS Manages isolation But, only isolation between processes Threads are not safe from each other file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 12/58 12

13 Thread dangers Threads can smash the stack of another thread, change that thread's data. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 13/58 13

14 But wait, there's more Scheduling (handwave): threads get a slice process's time in the CPU The process runs its threads during its time slice Switching between threads is cheap, switching between processes is expensive Don't need to load a process/load memory (threads share memory) file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 14/58 14

15 Great, why use processes? Threads are part of processes, therefore they execute on the same CPU Hyperthreading lets >1 execute at once... maybe. Multiple cores can execute multiple threads, depending on CPU archetecture. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 15/58 15

16 Why? Processes need to do many things Think about something that requires input from a user Users are PAINFULLY SLOW compared to a CPU 60 WPM \(\rightarrow\) 1hz. 1hz < hz file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 16/58 16

17 So 1 thread waiting for a human 1 thread waiting for disk or network I/O 1 thread updating something on the screen (progress bar) file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 17/58 17

18 I'm sold How! file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 18/58 18

19 Posix threads or, pthreads pthread_create - create a thread pthread_exit - kill a thread pthread_join - wait for threads to join file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 19/58 19

20 pthreads and compiling Compiling any code with pthreads requires we pass an link in a library: gcc lpthread Adding this to a makefile helps us not have to remember... file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 20/58 20

21 Simple threading The threads get work, never have to report back to the main process. Print to the screen Send data to the network Sadly, uncommon... See simple_thread.c file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 21/58 21

22 Thread pools Thread pools are a common programming pattern. Consider: program that fetches files from hard drive/network for consumption Any queryable service file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 22/58 22

23 Thread example Webservers Webservers are good examples of multithreaded software 1 thread waiting for requests Issues that request to a thread to fulfill. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 23/58 23

24 How would we do it? Conceptually main () { while (1) { req = getrequest() Thread t = new Thread() t.reply(req) } } file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 24/58 24

25 Webserver, reality Creating and destroying (or abandoning) threads is wasteful Concept: Create all the threads when we create the process. Reuse them to solve incoming work file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 25/58 25

26 Prerequisites for pooling This only works if: All the incoming work is similar We have a long-lived thread that issues requests This thread often listens for input file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 26/58 26

27 Issuing tasks How can we issue tasks to workers? Use shared memory? Threads share memory, so that's free! The workers poll for work This is a concurrency problem - solve this to get into pooling file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 27/58 27

28 Concurrency problems Operations aren't atomic They don't happen at once Two workers WILL fetch the same work. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 28/58 28

29 Concurrency, intro Problems: Two (or more) threads are attempting to access/change the same data They can't both change the data They shouldn't look at stale data file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 29/58 29

30 Critical section, intro If we are looking at data that can change, we need to lock it "I have the conch, I will speak" ONE thread is allowed to inspect/change a variable at a time file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 30/58 30

31 Mutual exclusion Me OR you are looking at this... not both xor! (x or y) and not (x and y) file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 31/58 31

32 Mutex What could possibly go wrong? Check out this code Is there anything else we can do to help? volatile? Reload from memory on each use file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 32/58 32

33 The tools Posix gives us these tools to work with: pthread_mutex_t - mutex variable pthread_mutex_lock - stop, wait for exclusive access pthread_mutex_unlock - free the lock when done pthread_mutex_trylock - non-blocking test of the lock file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 33/58 33

34 thread_clobber2.c Added a simple lock in this code Notice anything different? Much much much slower! Not really running in parallel, is it... file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 34/58 34

35 thread_clobber3.c Locking aggressively is a BAD idea. Blocks the other thread from doing any work. Called "starvation" - we starve the other thread from the resources it requires to run. Cleaned up how to parallelize this in this code file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 35/58 35

36 clobbering, conclusion It's easy to be naive with locking/threads Consider your problem Think about it as a parallel problem Can we lock less? Do we need to lock? file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 36/58 36

37 pthread_exit and pthread_join Threads are void* return type. Abstract! Can return anything This has to be allocated somewhere, though... Don't return a stack pointer! file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 37/58 37

38 Returning and catching Simply using return won't work... pthread_exit(valueptr) can return a value back to the caller pthread_join(mythread, valueptr) can catch that pointer, we can use it. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 38/58 38

39 Thread pools Many programs are queryable services 1 thread listens for incoming requests n threads process the request, return result to requester - called workers We need to issue tasks to the workers file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 39/58 39

40 Thread pool? Deadpool Wait, Thread pool (c) Marvel file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 40/58 40

41 Thread pools - tasks How do we issue tasks to workers? Threads make sharing memory simple Have a staging area for data that we are passing to workers Listener stores data in well-known shared location Worker copies data from shared buffer, does task file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 41/58 41

42 Issuing work What do we do when we get new work Need one (of many) threads to do the work Just one thread, not all of them Just one, you say... do we have tools for this? file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 42/58 42

43 Issuing work Of course! Mutex! Need a mutex to protect reading and writing the data being passed How do we intelligently check for new work file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 43/58 43

44 Why check? We can signal the threads that there is new work that needs to be consumed. Posix gives us condition variables. Condition variables block a thread until it is signaled that it can continue. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 44/58 44

45 Condition varibles Worker threads run a near-infinite loop - while (!done). Check for more work: pthread_mutex_lock( &workdatalock ); pthread_cond_wait( &workready, &workdatalock ); workready - condition variable workdatalock - mutex to lock the critical variables pthread_cond_wait unlocks the mutex, returns when the condition variable is signaled file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 45/58 45

46 pthread_cond_wait Great tool: Stop this thread, free lock, wait (blocked state). Returns when work appears, AND we have the lock. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 46/58 46

47 Query thread The query thread has to signal when new work has appeared. // wait for more work, put it in shared buffer // get the lock pthread_mutex_lock( &workdatalock ); databuffer = somedata; // signal that data is available pthread_cond_signal(&workready); pthread_mutex_unlock( &workdatalock ); file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 47/58 47

48 Explained: pthread_cond_signal wakes a thread, which will get the lock when we unlock workdatalock. (We don't need workdatalock... but...) file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 48/58 48

49 file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 49/58 49

50 In case you haven't watched The Holy Grail... It's not that easy. Does pthread_cond_signal wake just one thread? Of course not We need more condition variables to handle this problem... file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 50/58 50

51 pthread_cond_signal pattern pthread_mutex_lock( &workdatalock ); while (!workavailable) pthread_cond_wait( &workready, &workdatalock ); workavailable must be protected by lock. Many threads will wake, only one will see workavailable as true. The worker MUST COPY the data from the shared buffer, set workavailable to false. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 51/58 51

52 pthread_cond_signal pattern The query thread: Must wait for work to be consumed Oh look, another condition variable Workers signal query thread once work has been consumed (copied) file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 52/58 52

53 Example Waking threads to do something thread_signal.c thread_signal2.c file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 53/58 53

54 Are workers available? A few ways to know this: Query thread waits on workavailable == true until it is cleared Data is consumed This doesn't imply a thread is ready for a signal Have a counting variable - how many availble threads there are. Don't call pthread_cond_signal if no one is listening. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 54/58 54

55 Functions: pthread_cond_t - variable type for condition variables pthread_cond_init(&threadready, NULL); - init the conditions, optional attributes pthread_cond_wait(&threadready, &lock); - free the lock, wait on condition pthread_cond_signal&threadready); - Signal the waiting thread(s) pthread_cond_broadcast(&threadready); - Signal ALL waiting threads (good for cleanup) file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 55/58 55

56 Thread Pools, conclusion 1 Locks and conditions control the workflow of the workers We must wrangle the workers, signals must go both ways. file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 56/58 56

57 Thread Pools, conclusion 2 Can make thread pools more generic Pass function pointers, arguments to workers Run generic tasks! file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 57/58 57

58 References Good example Threads visualized Condition wait In-class code examples file:///users/robg/dropbox/teaching/ /slides/04_threads/index.html?print-pdf#/ 58/58 58

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

CSCI4430 Data Communication and Computer Networks. Pthread Programming. ZHANG, Mi Jan. 26, 2017 CSCI4430 Data Communication and Computer Networks Pthread Programming ZHANG, Mi Jan. 26, 2017 Outline Introduction What is Multi-thread Programming Why to use Multi-thread Programming Basic Pthread Programming

More information

THREADS. Jo, Heeseung

THREADS. Jo, Heeseung THREADS Jo, Heeseung TODAY'S TOPICS Why threads? Threading issues 2 PROCESSES Heavy-weight A process includes many things: - An address space (all the code and data pages) - OS resources (e.g., open files)

More information

TCSS 422: OPERATING SYSTEMS

TCSS 422: OPERATING SYSTEMS TCSS 422: OPERATING SYSTEMS OBJECTIVES Introduction to threads Concurrency: An Introduction Wes J. Lloyd Institute of Technology University of Washington - Tacoma Race condition Critical section Thread

More information

CS444 1/28/05. Lab 03

CS444 1/28/05. Lab 03 CS444 1/28/05 Lab 03 Note All the code that is found in this lab guide can be found at the following web address: www.clarkson.edu/class/cs444/cs444.sp2005/labs/lab03/code/ Threading A thread is an independent

More information

Synchronising Threads

Synchronising Threads Synchronising Threads David Chisnall March 1, 2011 First Rule for Maintainable Concurrent Code No data may be both mutable and aliased Harder Problems Data is shared and mutable Access to it must be protected

More information

POSIX Threads. HUJI Spring 2011

POSIX Threads. HUJI Spring 2011 POSIX Threads HUJI Spring 2011 Why Threads The primary motivation for using threads is to realize potential program performance gains and structuring. Overlapping CPU work with I/O. Priority/real-time

More information

Introduction to PThreads and Basic Synchronization

Introduction to PThreads and Basic Synchronization Introduction to PThreads and Basic Synchronization Michael Jantz, Dr. Prasad Kulkarni Dr. Douglas Niehaus EECS 678 Pthreads Introduction Lab 1 Introduction In this lab, we will learn about some basic synchronization

More information

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

CS Lecture 3! Threads! George Mason University! Spring 2010! CS 571 - Lecture 3! Threads! George Mason University! Spring 2010! Threads! Overview! Multithreading! Example Applications! User-level Threads! Kernel-level Threads! Hybrid Implementation! Observing Threads!

More information

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

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University 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

More information

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

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 Process creation in UNIX All processes have a unique process id getpid(),

More information

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University Threads Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu) Concurrency

More information

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

Thread. Disclaimer: some slides are adopted from the book authors slides with permission 1 Thread Disclaimer: some slides are adopted from the book authors slides with permission 1 IPC Shared memory Recap share a memory region between processes read or write to the shared memory region fast

More information

Computer Systems Laboratory Sungkyunkwan University

Computer Systems Laboratory Sungkyunkwan University Threads Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Today s Topics Why threads? Threading issues 2 Processes Heavy-weight A process includes

More information

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

EPL372 Lab Exercise 2: Threads and pthreads. Εργαστήριο 2. Πέτρος Παναγή EPL372 Lab Exercise 2: Threads and pthreads Εργαστήριο 2 Πέτρος Παναγή 1 Threads Vs Processes 2 Process A process is created by the operating system, and requires a fair amount of "overhead". Processes

More information

COMP 3430 Robert Guderian

COMP 3430 Robert Guderian Operating Systems COMP 3430 Robert Guderian file:///users/robg/dropbox/teaching/3430-2018/slides/06_concurrency/index.html?print-pdf#/ 1/76 1 Concurrency file:///users/robg/dropbox/teaching/3430-2018/slides/06_concurrency/index.html?print-pdf#/

More information

Multithreading Programming II

Multithreading Programming II Multithreading Programming II Content Review Multithreading programming Race conditions Semaphores Thread safety Deadlock Review: Resource Sharing Access to shared resources need to be controlled to ensure

More information

Concurrent Programming

Concurrent Programming Concurrent Programming is Hard! Concurrent Programming Kai Shen The human mind tends to be sequential Thinking about all possible sequences of events in a computer system is at least error prone and frequently

More information

POSIX PTHREADS PROGRAMMING

POSIX PTHREADS PROGRAMMING POSIX PTHREADS PROGRAMMING Download the exercise code at http://www-micrel.deis.unibo.it/~capotondi/pthreads.zip Alessandro Capotondi alessandro.capotondi(@)unibo.it Hardware Software Design of Embedded

More information

ENCM 501 Winter 2019 Assignment 9

ENCM 501 Winter 2019 Assignment 9 page 1 of 6 ENCM 501 Winter 2019 Assignment 9 Steve Norman Department of Electrical & Computer Engineering University of Calgary April 2019 Assignment instructions and other documents for ENCM 501 can

More information

Intro to POSIX Threads with FLTK

Intro to POSIX Threads with FLTK Intro to POSIX Threads with FLTK 25 Mar 2009 CMPT166 Dr. Sean Ho Trinity Western University See: FlChat/ example code Threads and parallelism Threads are lightweight processes Threads allow concurrency

More information

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

Lecture 4. Threads vs. Processes. fork() Threads. Pthreads. Threads in C. Thread Programming January 21, 2005 Threads vs. Processes Lecture 4 Thread Programming January 21, 2005 fork() is expensive (time, memory) Interprocess communication is hard. Threads are lightweight processes: one process can contain several

More information

CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 22 Shared-Memory Concurrency 1 Administrivia HW7 due Thursday night, 11 pm (+ late days if you still have any & want to use them) Course

More information

C Grundlagen - Threads

C Grundlagen - Threads Michael Strassberger saremox@linux.com Proseminar C Grundlagen Fachbereich Informatik Fakultaet fuer Mathematik, Informatik und Naturwissenschaften Universitaet Hamburg 3. Juli 2014 Table of Contents 1

More information

Processes. 4: Threads. Problem needs > 1 independent sequential process? Example: Web Server. Last Modified: 9/17/2002 2:27:59 PM

Processes. 4: Threads. Problem needs > 1 independent sequential process? Example: Web Server. Last Modified: 9/17/2002 2:27:59 PM Processes 4: Threads Last Modified: 9/17/2002 2:27:59 PM Recall: A process includes Address space (Code, Data, Heap, Stack) Register values (including the PC) Resources allocated to the process Memory,

More information

Concurrent Programming

Concurrent Programming Concurrent Programming is Hard! Concurrent Programming Kai Shen The human mind tends to be sequential Thinking about all possible sequences of events in a computer system is at least error prone and frequently

More information

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

Outline. CS4254 Computer Network Architecture and Programming. Introduction 2/4. Introduction 1/4. Dr. Ayman A. Abdel-Hamid. Threads Dr. Ayman Abdel-Hamid, CS4254 Spring 2006 1 CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department Virginia Tech Threads Outline Threads (Chapter

More information

CSE 153 Design of Operating Systems

CSE 153 Design of Operating Systems CSE 153 Design of Operating Systems Winter 19 Lecture 7/8: Synchronization (1) Administrivia How is Lab going? Be prepared with questions for this weeks Lab My impression from TAs is that you are on track

More information

CS 261 Fall Mike Lam, Professor. Threads

CS 261 Fall Mike Lam, Professor. Threads CS 261 Fall 2017 Mike Lam, Professor Threads Parallel computing Goal: concurrent or parallel computing Take advantage of multiple hardware units to solve multiple problems simultaneously Motivations: Maintain

More information

POSIX Threads. Paolo Burgio

POSIX Threads. Paolo Burgio POSIX Threads Paolo Burgio paolo.burgio@unimore.it The POSIX IEEE standard Specifies an operating system interface similar to most UNIX systems It extends the C language with primitives that allows the

More information

Motivation and definitions Processes Threads Synchronization constructs Speedup issues

Motivation and definitions Processes Threads Synchronization constructs Speedup issues Motivation and definitions Processes Threads Synchronization constructs Speedup issues Overhead Caches Amdahl s Law CS550: Advanced Operating Systems 2 If task can be completely decoupled into independent

More information

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks CSci 4061 Introduction to Operating Systems Synchronization Basics: Locks Synchronization Outline Basics Locks Condition Variables Semaphores Basics Race condition: threads + shared data Outcome (data

More information

CS 3723 Operating Systems: Final Review

CS 3723 Operating Systems: Final Review CS 3723 Operating Systems: Final Review Outline Threads Synchronizations Pthread Synchronizations Instructor: Dr. Tongping Liu 1 2 Threads: Outline Context Switches of Processes: Expensive Motivation and

More information

TCSS 422: OPERATING SYSTEMS

TCSS 422: OPERATING SYSTEMS TCSS 422: OPERATING SYSTEMS Concurrency: An Introduction Wes J. Lloyd Institute of Technology University of Washington - Tacoma FEEDBACK FROM 1/23 Are there larger overhead costs for any particular type

More information

LSN 13 Linux Concurrency Mechanisms

LSN 13 Linux Concurrency Mechanisms LSN 13 Linux Concurrency Mechanisms ECT362 Operating Systems Department of Engineering Technology LSN 13 Creating Processes fork() system call Returns PID of the child process created The new process is

More information

ECE 574 Cluster Computing Lecture 8

ECE 574 Cluster Computing Lecture 8 ECE 574 Cluster Computing Lecture 8 Vince Weaver http://web.eece.maine.edu/~vweaver vincent.weaver@maine.edu 16 February 2017 Announcements Too many snow days Posted a video with HW#4 Review HW#5 will

More information

COSC 6374 Parallel Computation. Shared memory programming with POSIX Threads. Edgar Gabriel. Fall References

COSC 6374 Parallel Computation. Shared memory programming with POSIX Threads. Edgar Gabriel. Fall References COSC 6374 Parallel Computation Shared memory programming with POSIX Threads Fall 2012 References Some of the slides in this lecture is based on the following references: http://www.cobweb.ecn.purdue.edu/~eigenman/ece563/h

More information

Distributed systems. Programming with threads

Distributed systems. Programming with threads Distributed systems Programming with threads Reviews on OS concepts Each process occupies a single address space Reviews on OS concepts A thread of (execution) control has its own PC counter, stack pointer

More information

CS333 Intro to Operating Systems. Jonathan Walpole

CS333 Intro to Operating Systems. Jonathan Walpole CS333 Intro to Operating Systems Jonathan Walpole Threads & Concurrency 2 Threads Processes have the following components: - an address space - a collection of operating system state - a CPU context or

More information

CS 105, Spring 2015 Ring Buffer

CS 105, Spring 2015 Ring Buffer CS 105, Spring 2015 Ring Buffer March 10, 2015 1 Introduction A ring buffer, also called a circular buffer, is a common method of sharing information between a producer and a consumer. In class, we have

More information

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

High Performance Computing Lecture 21. Matthew Jacob Indian Institute of Science High Performance Computing Lecture 21 Matthew Jacob Indian Institute of Science Semaphore Examples Semaphores can do more than mutex locks Example: Consider our concurrent program where process P1 reads

More information

CS 326: Operating Systems. Process Execution. Lecture 5

CS 326: Operating Systems. Process Execution. Lecture 5 CS 326: Operating Systems Process Execution Lecture 5 Today s Schedule Process Creation Threads Limited Direct Execution Basic Scheduling 2/5/18 CS 326: Operating Systems 2 Today s Schedule Process Creation

More information

real time operating systems course

real time operating systems course real time operating systems course 4 introduction to POSIX pthread programming introduction thread creation, join, end thread scheduling thread cancellation semaphores thread mutexes and condition variables

More information

Threads. Threads (continued)

Threads. Threads (continued) Threads A thread is an alternative model of program execution A process creates a thread through a system call Thread operates within process context Use of threads effectively splits the process state

More information

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

Processes Prof. James L. Frankel Harvard University. Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved. Processes Prof. James L. Frankel Harvard University Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved. Process Model Each process consists of a sequential program

More information

Concurrency, Thread. Dongkun Shin, SKKU

Concurrency, Thread. Dongkun Shin, SKKU Concurrency, Thread 1 Thread Classic view a single point of execution within a program a single PC where instructions are being fetched from and executed), Multi-threaded program Has more than one point

More information

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

Synchronization. CS61, Lecture 18. Prof. Stephen Chong November 3, 2011 Synchronization CS61, Lecture 18 Prof. Stephen Chong November 3, 2011 Announcements Assignment 5 Tell us your group by Sunday Nov 6 Due Thursday Nov 17 Talks of interest in next two days Towards Predictable,

More information

Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective?

Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective? Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective? CS 470 Spring 2019 POSIX Mike Lam, Professor Multithreading & Pthreads MIMD

More information

POSIX / System Programming

POSIX / System Programming POSIX / System Programming ECE 650 Methods and Tools for Software Eng. Guest lecture 2017 10 06 Carlos Moreno cmoreno@uwaterloo.ca E5-4111 2 Outline During today's lecture, we'll look at: Some of POSIX

More information

COSC 2P95 Lab 9 Signals, Mutexes, and Threads

COSC 2P95 Lab 9 Signals, Mutexes, and Threads COSC 2P95 Lab 9 Signals, Mutexes, and Threads Sometimes, we can't achieve what we want via a single execution pipeline. Whether it's for responsiveness, or to process more data simultaneously, we rely

More information

Paralleland Distributed Programming. Concurrency

Paralleland Distributed Programming. Concurrency Paralleland Distributed Programming Concurrency Concurrency problems race condition synchronization hardware (eg matrix PCs) software (barrier, critical section, atomic operations) mutual exclusion critical

More information

CSE 153 Design of Operating Systems Fall 2018

CSE 153 Design of Operating Systems Fall 2018 CSE 153 Design of Operating Systems Fall 2018 Lecture 5: Threads/Synchronization Implementing threads l Kernel Level Threads l u u All thread operations are implemented in the kernel The OS schedules all

More information

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CMPSC 311- Introduction to Systems Programming Module: Concurrency CMPSC 311- Introduction to Systems Programming Module: Concurrency Professor Patrick McDaniel Fall 2013 Sequential Programming Processing a network connection as it arrives and fulfilling the exchange

More information

CS533 Concepts of Operating Systems. Jonathan Walpole

CS533 Concepts of Operating Systems. Jonathan Walpole CS533 Concepts of Operating Systems Jonathan Walpole Introduction to Threads and Concurrency Why is Concurrency Important? Why study threads and concurrent programming in an OS class? What is a thread?

More information

Operating systems and concurrency (B08)

Operating systems and concurrency (B08) Operating systems and concurrency (B08) David Kendall Northumbria University David Kendall (Northumbria University) Operating systems and concurrency (B08) 1 / 20 Introduction Semaphores provide an unstructured

More information

Solving the Producer Consumer Problem with PThreads

Solving the Producer Consumer Problem with PThreads Solving the Producer Consumer Problem with PThreads Michael Jantz Dr. Prasad Kulkarni Dr. Douglas Niehaus EECS 678 Pthreads: Producer-Consumer 1 Introduction This lab is an extension of last week's lab.

More information

Last class: Today: Thread Background. Thread Systems

Last class: Today: Thread Background. Thread Systems 1 Last class: Thread Background Today: Thread Systems 2 Threading Systems 3 What kind of problems would you solve with threads? Imagine you are building a web server You could allocate a pool of threads,

More information

Shared Memory Programming. Parallel Programming Overview

Shared Memory Programming. Parallel Programming Overview Shared Memory Programming Arvind Krishnamurthy Fall 2004 Parallel Programming Overview Basic parallel programming problems: 1. Creating parallelism & managing parallelism Scheduling to guarantee parallelism

More information

CS 105, Spring 2007 Ring Buffer

CS 105, Spring 2007 Ring Buffer CS 105, Spring 2007 Ring Buffer April 11, 2007 1 Introduction A ring buffer, also called a circular buffer, is a common method of sharing information between a producer and a consumer. In class, we have

More information

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole CS510 Operating System Foundations Jonathan Walpole Threads & Concurrency 2 Why Use Threads? Utilize multiple CPU s concurrently Low cost communication via shared memory Overlap computation and blocking

More information

High Performance Computing Course Notes Shared Memory Parallel Programming

High Performance Computing Course Notes Shared Memory Parallel Programming High Performance Computing Course Notes 2009-2010 2010 Shared Memory Parallel Programming Techniques Multiprocessing User space multithreading Operating system-supported (or kernel) multithreading Distributed

More information

Concurrent Server Design Multiple- vs. Single-Thread

Concurrent Server Design Multiple- vs. Single-Thread Concurrent Server Design Multiple- vs. Single-Thread Chuan-Ming Liu Computer Science and Information Engineering National Taipei University of Technology Fall 2007, TAIWAN NTUT, TAIWAN 1 Examples Using

More information

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

Concurrency and Synchronization. ECE 650 Systems Programming & Engineering Duke University, Spring 2018 Concurrency and Synchronization ECE 650 Systems Programming & Engineering Duke University, Spring 2018 Concurrency Multiprogramming Supported by most all current operating systems More than one unit of

More information

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

Threads need to synchronize their activities to effectively interact. This includes: KING FAHD UNIVERSITY OF PETROLEUM AND MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 8 Threads Synchronization ( Mutex & Condition Variables ) Objective: When multiple

More information

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; }

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; } Semaphore Semaphore S integer variable Two standard operations modify S: wait() and signal() Originally called P() and V() Can only be accessed via two indivisible (atomic) operations wait (S) { while

More information

CS 3305 Intro to Threads. Lecture 6

CS 3305 Intro to Threads. Lecture 6 CS 3305 Intro to Threads Lecture 6 Introduction Multiple applications run concurrently! This means that there are multiple processes running on a computer Introduction Applications often need to perform

More information

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

Questions answered in this lecture: CS 537 Lecture 19 Threads and Cooperation. What s in a process? Organizing a Process Questions answered in this lecture: CS 537 Lecture 19 Threads and Cooperation Why are threads useful? How does one use POSIX pthreads? Michael Swift 1 2 What s in a process? Organizing a Process A process

More information

CS516 Programming Languages and Compilers II

CS516 Programming Languages and Compilers II CS516 Programming Languages and Compilers II Zheng Zhang Spring 2015 Mar 12 Parallelism and Shared Memory Hierarchy I Rutgers University Review: Classical Three-pass Compiler Front End IR Middle End IR

More information

Introduction to pthreads

Introduction to pthreads CS 220: Introduction to Parallel Computing Introduction to pthreads Lecture 25 Threads In computing, a thread is the smallest schedulable unit of execution Your operating system has a scheduler that decides

More information

ANSI/IEEE POSIX Standard Thread management

ANSI/IEEE POSIX Standard Thread management Pthread Prof. Jinkyu Jeong( jinkyu@skku.edu) TA Jinhong Kim( jinhong.kim@csl.skku.edu) TA Seokha Shin(seokha.shin@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu The

More information

Deviations are things that modify a thread s normal flow of control. Unix has long had signals, and these must be dealt with in multithreaded

Deviations are things that modify a thread s normal flow of control. Unix has long had signals, and these must be dealt with in multithreaded Deviations are things that modify a thread s normal flow of control. Unix has long had signals, and these must be dealt with in multithreaded improvements to Unix. There are actually two fairly different

More information

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CMPSC 311- Introduction to Systems Programming Module: Concurrency CMPSC 311- Introduction to Systems Programming Module: Concurrency Professor Patrick McDaniel Fall 2013 Sequential Programming Processing a network connection as it arrives and fulfilling the exchange

More information

pthreads CS449 Fall 2017

pthreads CS449 Fall 2017 pthreads CS449 Fall 2017 POSIX Portable Operating System Interface Standard interface between OS and program UNIX-derived OSes mostly follow POSIX Linux, macos, Android, etc. Windows requires separate

More information

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CMPSC 311- Introduction to Systems Programming Module: Concurrency CMPSC 311- Introduction to Systems Programming Module: Concurrency Professor Patrick McDaniel Fall 2016 Sequential Programming Processing a network connection as it arrives and fulfilling the exchange

More information

Lecture 13 Condition Variables

Lecture 13 Condition Variables Lecture 13 Condition Variables Contents In this lecture, you will learn Condition Variables And how to use CVs to solve The Producer/Consumer (Bounded Buffer) Problem Review Thus far we have developed

More information

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

Programming with Shared Memory. Nguyễn Quang Hùng Programming with Shared Memory Nguyễn Quang Hùng Outline Introduction Shared memory multiprocessors Constructs for specifying parallelism Creating concurrent processes Threads Sharing data Creating shared

More information

A Brief Introduction to OS/2 Multithreading

A Brief Introduction to OS/2 Multithreading A Brief Introduction to OS/2 Multithreading Jaroslav Kaƒer jkacer@kiv.zcu.cz University of West Bohemia Faculty of Applied Sciences Department of Computer Science and Engineering Why Use Parallelism? Performance

More information

Chapter 4 Concurrent Programming

Chapter 4 Concurrent Programming Chapter 4 Concurrent Programming 4.1. Introduction to Parallel Computing In the early days, most computers have only one processing element, known as the Central Processing Unit (CPU). Due to this hardware

More information

User Space Multithreading. Computer Science, University of Warwick

User Space Multithreading. Computer Science, University of Warwick User Space Multithreading 1 Threads Thread short for thread of execution/control B efore create Global During create Global Data Data Executing Code Code Stack Stack Stack A fter create Global Data Executing

More information

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University Pthreads Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu The Pthreads API ANSI/IEEE POSIX1003.1-1995 Standard Thread management Work directly on

More information

Locks and semaphores. Johan Montelius KTH

Locks and semaphores. Johan Montelius KTH Locks and semaphores Johan Montelius KTH 2017 1 / 41 recap, what s the problem : # include < pthread.h> volatile int count = 0; void * hello ( void * arg ) { for ( int i = 0; i < 10; i ++) { count ++;

More information

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

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization CS-345 Operating Systems Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization Threads A thread is a lightweight process A thread exists within a process and uses the process resources. It

More information

ECE 598 Advanced Operating Systems Lecture 23

ECE 598 Advanced Operating Systems Lecture 23 ECE 598 Advanced Operating Systems Lecture 23 Vince Weaver http://web.eece.maine.edu/~vweaver vincent.weaver@maine.edu 21 April 2016 Don t forget HW#9 Midterm next Thursday Announcements 1 Process States

More information

Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017

Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017 Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017 Data Race Shared Data: 465 1 8 5 6 209? tail A[] thread switch Enqueue(): A[tail] = 20; tail++; A[tail] = 9; tail++; Thread 0 Thread

More information

Concurrency and Threads

Concurrency and Threads 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

More information

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

Agenda. Process vs Thread. ! POSIX Threads Programming. Picture source: Agenda POSIX Threads Programming 1 Process vs Thread process thread Picture source: https://computing.llnl.gov/tutorials/pthreads/ 2 Shared Memory Model Picture source: https://computing.llnl.gov/tutorials/pthreads/

More information

Locks and semaphores. Johan Montelius KTH

Locks and semaphores. Johan Montelius KTH Locks and semaphores Johan Montelius KTH 2018 1 / 40 recap, what s the problem : # include < pthread.h> volatile int count = 0; void * hello ( void * arg ) { for ( int i = 0; i < 10; i ++) { count ++;

More information

Condition Variables. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Condition Variables. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University Condition Variables Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu)

More information

COMP 3430 Robert Guderian

COMP 3430 Robert Guderian Operating Systems COMP 3430 Robert Guderian file:///users/robg/dropbox/teaching/3430-2018/slides/03_processes/index.html?print-pdf#/ 1/53 1 Processes file:///users/robg/dropbox/teaching/3430-2018/slides/03_processes/index.html?print-pdf#/

More information

CS 153 Design of Operating Systems Winter 2016

CS 153 Design of Operating Systems Winter 2016 CS 153 Design of Operating Systems Winter 2016 Lecture 7: Synchronization Administrivia Homework 1 Due today by the end of day Hopefully you have started on project 1 by now? Kernel-level threads (preemptable

More information

Programming in Parallel COMP755

Programming in Parallel COMP755 Programming in Parallel COMP755 All games have morals; and the game of Snakes and Ladders captures, as no other activity can hope to do, the eternal truth that for every ladder you hope to climb, a snake

More information

Threads. Jo, Heeseung

Threads. Jo, Heeseung Threads Jo, Heeseung Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2 Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU

More information

Concurrency: Threads. CSE 333 Autumn 2018

Concurrency: Threads. CSE 333 Autumn 2018 Concurrency: Threads CSE 333 Autumn 2018 Instructor: Hal Perkins Teaching Assistants: Tarkan Al-Kazily Renshu Gu Trais McGaha Harshita Neti Thai Pham Forrest Timour Soumya Vasisht Yifan Xu Administriia

More information

by Marina Cholakyan, Hyduke Noshadi, Sepehr Sahba and Young Cha

by Marina Cholakyan, Hyduke Noshadi, Sepehr Sahba and Young Cha CS 111 Scribe Notes for 4/11/05 by Marina Cholakyan, Hyduke Noshadi, Sepehr Sahba and Young Cha Processes What is a process? A process is a running instance of a program. The Web browser you're using to

More information

Threads. CS3026 Operating Systems Lecture 06

Threads. CS3026 Operating Systems Lecture 06 Threads CS3026 Operating Systems Lecture 06 Multithreading Multithreading is the ability of an operating system to support multiple threads of execution within a single process Processes have at least

More information

More Shared Memory Programming

More Shared Memory Programming More Shared Memory Programming Shared data structures We want to make data structures that can be shared by threads. For example, our program to copy a file from one disk to another used a shared FIFO

More information

Introduction to parallel computing

Introduction to parallel computing Introduction to parallel computing Shared Memory Programming with Pthreads (3) Zhiao Shi (modifications by Will French) Advanced Computing Center for Education & Research Vanderbilt University Last time

More information

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

CS 31: Introduction to Computer Systems : Threads & Synchronization April 16-18, 2019 CS 31: Introduction to Computer Systems 22-23: Threads & Synchronization April 16-18, 2019 Making Programs Run Faster We all like how fast computers are In the old days (1980 s - 2005): Algorithm too slow?

More information

4. Concurrency via Threads

4. Concurrency via Threads CSC400 - Operating Systems 4. Concurrency via Threads J. Sumey Overview Multithreading Concept Background Implementations Thread States & Thread Switching Thread Operations Case Study: pthreads CSC400

More information

Threads Tuesday, September 28, :37 AM

Threads Tuesday, September 28, :37 AM Threads_and_fabrics Page 1 Threads Tuesday, September 28, 2004 10:37 AM Threads A process includes an execution context containing Memory map PC and register values. Switching between memory maps can take

More information

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

CS 153 Lab4 and 5. Kishore Kumar Pusukuri. Kishore Kumar Pusukuri CS 153 Lab4 and 5 CS 153 Lab4 and 5 Kishore Kumar Pusukuri Outline Introduction A thread is a straightforward concept : a single sequential flow of control. In traditional operating systems, each process has an address

More information