Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

Size: px
Start display at page:

Download "Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University"

Transcription

1 Concurrent Programming Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University 1

2 Objectives You will learn/review: What a process is How to fork and wait for processes What a thread is How to spawn and join threads How to handle threads that access shared objects Race conditions and prevention of them Deadlocks and prevention of them How processes can communicate How threads can communicate 2

3 Agenda 1. Process-level concurrency (C) 2. Thread-level concurrency (Java/Python) 3. Race conditions (Java/Python) 4. Deadlock (Java/Python) 5. Inter-process comm (C) 6. Inter-thread comm (Java/Python) 3

4 Processes Program Executable code Process An instance of a program in execution A process has its own distinct context 4

5 Process Context Context consists of: Process id Address space: TEXT, RODATA, DATA, BSS, HEAP, STACK Processor state: RIP, EFLAGS, RAX, RBX, etc. registers 5

6 Concurrency Options To implement concurrency... Option 1: Multiple processes Process P1 forks process P2 P1 and P2 execute concurrently P1 and P2 do not share objects P1 and P2 have (initially identical but) distinct memory spaces (Relatively) expensive context switching 6

7 Concurrent Processes Concurrent Processes Running Same Program PROCESS 1 PROCESS 2 HEAP STACK RODATA STACK HEAP DATA TEXT DATA BSS BSS IP REG IP REG 7

8 Process-Level Concurrency At system boot-up... Several processes are created automatically They run concurrently When you login... ssh process forks a child process Child process execs (overwrites itself with) your login shell (e.g. bash) ssh process and your login shell process run concurrently 8

9 Process-Level Concurrency When you execute your program as a command... Bash forks a child process Child process execs (overwrites itself with) your program Bash process and your process run concurrently Your process can fork/exec additional processes as desired Your process and child processes run concurrently 9

10 Process-Level Concurrency COS 333 example CGI programming When HTTP server receives HTTP request: HTTP server forks a child process Child process execs (overwrites itself with) the specified CGI program Parent HTTP server process and CGI process run concurrently 10

11 Forking Processes How to fork child processes? See forking.c Parent process forks blue child process and red child process Three processes execute concurrently Parent process may exit before child processes Malformed!!! A parent should wait for its children to exit A parent should reap its children 11

12 Waiting for Processes See waiting.c Parent waits for (reaps) its children Parent process is blocked until both children exit Proper pattern 12

13 Agenda 1. Process-level concurrency (C) 2. Thread-level concurrency (Java/ Python) 3. Race conditions (Java/Python) 4. Deadlock (Java/Python) 5. Inter-process comm (C) 6. Inter-thread comm (Java/Python) 13

14 Threads Thread A flow of control within a process A process contains one or more threads Within a process, all threads execute concurrently 14

15 Concurrency Options To implement concurrency Option 2: Multiple threads Within P1, thread T1 spawns thread T2 T1 and T2 execute concurrently T1 and T2 may share some of P1 s objects (Relatively) inexpensive context switching 15

16 Concurrent Threads Concurrent Threads within Same Process THREAD 1 THREAD 2 STACK RODATA DATA STACK IP REG HEAP BSS IP REG TEXT 16

17 Thread-Level Concurrency COS 333 examples Java virtual machine process JVM process must execute given program JVM process also must collect garbage Main thread and garbage collector thread run concurrently 17

18 Thread-Level Concurrency COS 333 examples Assignment 2 server process Server process must communicate with client process for (relatively) long time periods Server process also must respond to other client processes Server process spawns distinct thread for each client request Main thread and client handler thread run concurrently 18

19 Thread-Level Concurrency COS 333 examples Assignment 4 browser process Browser process must fetch data Browser process also must respond to user input Via AJAX, Browser main (UI) thread spawns a child thread to fetch data Browser main (UI) thread and fetch data thread run concurrently 19

20 Spawning Threads The main thread runs at process startup Other threads may run at process startup too The main thread can spawn other threads Note terminology: One process forks another One thread spawns another 20

21 Spawning Threads in Java See Spawning.java To spawn a thread: Define a subclass of Thread Override run() method Create an object of that class To begin execution of a thread: Call object s start() method start() calls run() Don t call run() directly 21

22 Spawning Threads in Java See RunnableInterface.java Alternative way to spawn a thread: Define class that implements Runnable Must define a run() method Create a Thread object specifying Runnable object as argument 22

23 Spawning Threads in Java To begin execution: Call Runnable object s start() method start() calls run() Don t call run() directly Useful when class extends some class other than Thread 23

24 Spawning Threads in Python See spawning.py (Much the same as Java) No need for Runnable interface approach Python supports multiple inheritance 24

25 Joining Threads Main thread can join a child thread Main thread can block until child thread terminates Terminology A parent process can wait for a child process A parent thread can join a child thread 25

26 Joining Threads in Java See Joining.java thread.join() Blocks current thread until thread terminates May throw InterruptedException (Explained in Appendix) 26

27 Joining Threads in Python See joining.py (Much the same) 27

28 Agenda 1. Process-level concurrency (C) 2. Thread-level concurrency (Java/Python) 3. Race conditions (Java/Python) 4. Deadlock (Java/Python) 5. Inter-process comm (C) 6. Inter-thread comm (Java/Python) 28

29 Race Conditions Problem: Threads can share objects Danger if multiple threads update same object Race condition Outcome depends upon thread scheduling See RaceCondition.java See racecondition.py 29

30 Locking Solution: Locking Current thread gets lock on shared object Thereby current thread has exclusive use of shared object Other threads cannot obtain lock on shared object until current thread releases lock Adds lots of overhead 30

31 User-Level Locking Approach 1: Locking in user of shared object 31

32 User-Level Locking in Java See LockInUser.java synchronized(sharedobj) { stmt; stmt; } Current thread: Give me the lock on sharedobj Other threads cannot obtain the lock on sharedobj during execution of block 32

33 User-Level Locking in Python See lockinuser.py self._lock = Lock() In BankAcct constructor Creates a lock for the newly instantiated object self._bankacct.getlock().acquire() In each thread Give me the lock on the bankacct object self._bankacct.getlock().release() In each thread Release the lock on the bankacct object 33

34 Resource-Level Locking Approach 2: Locking in shared resource/ object itself 34

35 Java Resource-Level Locking See LockInResource.java public synchronized void method() { } Is the same as: public void method() { synchronized(this) { } } Each BankAcct object thus is thread-safe 35

36 Python Resource-Level Locking See lockinresource.py Same, except... Locking is performed by BankAcct object rather than by thread objects Each BankAcct object thus is thread-safe 36

37 Locking Strategies Which locking approach is better? Resource-level locking Generally safer; shared object is thread-safe User-level locking Generally faster; avoids locking when unnecessary Maybe easier to understand? 37

38 Aside: Thread-Safe Collections Thread-safe collections in Java: Vector myvector = new Vector(); Hashmap mymap = new Hashmap(); List<E> mylist = new Collections.synchronizedList(new ArrayList<E>()); Map<K,V> mymap = new Collections.synchronizedMap(new HashMap<K,V>()); ConcurrentLinkedQueue<E> myqueue = new ConcurrentLinkedQueue<E>(); ConcurrentSkipListSet<E> myset = new ConcurrentSkipListSet<E>(); ConcurrentHashMap<K,V> mymap = new ConcurrentHashMap<K,V>(); ConcurrentSkipListMap<K,V> mymap = new ConcurrentSkipListMap<K,V>(); 38

39 Aside: Thread-Safe Collections Thread-safe collections in Python: from Queue import Queue myqueue = Queue() 39

40 Conditions Problem: Thread may need to wait for some condition on a locked object to become true Example: Withdraw thread must wait for bank account balance to be sufficiently large Solution: Conditions 40

41 Conditions Called from within locked code object.wait() Blocks current thread until it is notified Releases the lock object.notifyall() Notifies all waiting threads That some significant event has occurred Thread then should re-check condition 41

42 Conditions Pattern Thread conditions pattern: consumer() while (! condition) wait(); // Do what should be done when // condition is true. producer() // Change condition. notifyall(); 42

43 Java Conditions See Conditions.java Consumer method calls object.wait() repeatedly until condition is true Producer method calls object.notifyall() Could handle conditions in users rather than in shared resource 43

44 Python Conditions See conditions.py Condition wraps around lock Could handle conditions in users rather than in shared resource 44

45 Agenda 1. Process-level concurrency (C) 2. Thread-level concurrency (Java/Python) 3. Race conditions (Java/Python) 4. Deadlock (Java/Python) 5. Inter-process comm (C) 6. Inter-thread comm (Java/Python) 45

46 Deadlock Problem: deadlock Two threads: t1 and t2 Two shared objects: o1 and o2 t1 has lock on o1; needs lock on o2 t2 has lock on o2; needs lock on o1 Both threads block forever 46

47 Java Deadlock Example See Deadlock.java Deadlock (1) run() (2) run() transferthread1 transferthread2 (3) aliceacct.transferoneto(bobacct) (4) bobacct.transferoneto(aliceacct) aliceacct (5) bobacct.depositone() (6) aliceacct.depositone() bobacct 47

48 Python Deadlock Example See deadlock.py (Same pattern) 48

49 Preventing Deadlock Conditions for deadlock Mutual exclusion Hold and wait No preemption Circular chain of events Solution OS level: Negate one of the four conditions App level: Negate circular chain of events 49

50 Preventing Deadlock NoDeadlock Mutex (1) run() (2) run() transferthread1 (3) get lock (6) release lock (7) get lock (10) release lock transferthread2 (4) alictacct.transferoneto(bobacct) (8) bobacct.transferoneto(aliceacct) aliceacct (5) bobacct.withdrawone() (9) aliceacct.withdrawone() bobacct 50

51 Java Preventing Deadlock See NoDeadlock1.java Mutex object See NoDeadlock2.java Static fields and static methods Mutex object as a static field in BankAcct class See NoDeadlock3.java Really no need for Mutex object! Any object will suffice E.g., the object which represents the BankAcct class! 51

52 Python Preventing Deadlock See nodeadlock1.py Mutex object See nodeadlock2.py Static fields and static methods Mutex object as a static field in BankAcct class 52

53 Agenda 1. Process-level concurrency (C) 2. Thread-level concurrency (Java/Python) 3. Race conditions (Java/Python) 4. Deadlock (Java/Python) 5. Inter-process comm (C) 6. Inter-thread comm (Java/Python) 53

54 Inter-Process Comm Facts: Processes on different computers can communicate via sockets See Network lecture Processes on the same computer can communicate via pipes A Unix pipe is a queue for inter-process comm 54

55 Inter-Process Comm See childtochild.c Parent process creates producer and consumer child processes Producer child process writes data to pipe Consumer child process reads data from pipe 55

56 Inter-Process Comm See sortmore.c Parent process forks two child processes First child executes sort somefile With stdout redirected to pipe Second child executes more With stdin redirected to pipe 56

57 Inter-Process Comm Generalization Unix users routinely command the shell to fork communicating concurrent processes E.g. sort somefile more sortmore.c is a hardcoded shell 57

58 Agenda 1. Process-level concurrency (C) 2. Thread-level concurrency (Java/Python) 3. Race conditions (Java/Python) 4. Deadlock (Java/Python) 5. Inter-process comm (C) 6. Inter-thread comm (Java/Python) 58

59 Inter-Thread Comm Facts: Threads can communicate via shared objects Communication via shared objects is dangerous (race conditions, deadlock) Often threads are in a producer/consumer relationship Is there a safer way for producer/ consumer threads to communicate? 59

60 Java Inter-Thread Comm See ProdConStream.java PipedOutputStream and PipedInputStream Allow producer thread to send data to consumer thread See also java.io.pipedwriter and PipedReader for sending Unicode characters 60

61 Python Inter-Thread Comm See prodconstream.py No stream mechanism Can t implement Unix pipes model Can t implement Java stream model Instead... Queue class Methods are synchronized Producer thread puts to queue object Consumer thread gets from queue object 61

62 Concurrency Commentary Process-level concurrency is: Essential (Unix relies on it) Safe (distinct processes share no data) Thread-level concurrency is: Essential (garbage collection, network pgmming, web pgmming, ) Dangerous!!! (distinct threads can share objects) 62

63 Concurrency Commentary Should methods be synchronized by default? When using thread-level concurrency, should we avoid shared objects? Should we use process-level concurrency instead of thread-level concurrency whenever possible? In the long run, is thread-level concurrency a passing phase? 63

64 Summary We have covered: What a process is How to fork and wait for processes What a thread is How to spawn and join threads How to handle threads that access shared objects Race conditions and prevention of them Deadlocks and prevention of them How processes can communicate How threads can communicate 64

65 Appendix 1: Interrupting Threads 65

66 Interrupting Threads Bad idea to end a thread abnormally May leave shared objects in inconsistent states How to force normal thread termination? That is, how to force normal return from run()? 66

67 Interrupting Threads Forcing normal thread termination Define interrupted flag in thread object Initially set to false Define public thread.interrupt() method Called (by main thread?) to set interrupted flag to true run() checks interrupted flag periodically true => return from run() 67

68 Interrupting Threads Problem If thread is joining/waiting/sleeping, then Thread might not check flag for a long time Solution Interrupting threads 68

69 Java Interrupting Threads b = thread.interrupted() Returns the value (True or False) of thread s interrupted flag thread.interrupt() Sets thread s interrupted flag If thread is joining, waiting, or sleeping... join(), wait(), or sleep() throws InterruptedException Thread.interrupted() Checks interrupted flag of current thread 69

70 Java Interrupting Threads Suppose Main thread spawns thread t1 Main thread later calls t1.interrupt() What happens? if t1 is running, then t1.interrupt() sets t1 s interrupted flag to True t1.run() calls b = t1.interrupted() at leading edge of its loop b is True => t1.run() returns, and thread terminates else // t1 is blocked (for joining, waiting, or sleeping) join(), wait(), or sleep() throws an InterruptedException t1 catches the InterruptedException Catch clause re-calls t1.interrupt() 70

71 Java Interrupting Threads Pattern in thread object: public void run() { while ( ) { if (interrupted()) return; } } Pattern in thread object: try { Thread.sleep(1000); } catch (InterruptedException e) { interrupt(); } Pattern in non-thread object: try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } 71

72 Java Interrupting Threads See Interrupting.java 72

73 Python Interrupting Threads Not supported!!! Threads cannot be controlled from the outside (Java is particularly good for multithreaded programming) 73

74 Appendix 2: Daemon Threads 74

75 Daemon Threads User thread (as seen so far) Example: thread that calls main() Process exits when all user threads have terminated Daemon thread Example: garbage collector thread Exists only to service other threads Process can terminate with running daemon threads 75

76 Java Daemon Threads thread.setdaemon(b) Sets daemon status of thread to b (true or false) b = thread.isdaemon() Returns daemon status of thread See Daemons.java Daemon threads end when main thread ends 76

77 Python Daemon Threads thread.setdaemon(b) Sets daemon status of thread to b (True or False) b = thread.isdaemon() Returns daemon status of thread See daemons.py Daemon threads end when main thread ends 77

78 Appendix 3: Threads in C 78

79 Threads in C C language does not support threads C standard library does not support threads Use non-standard pthreads library Not object-oriented; uses function pointers Specify -pthread option to gcc command 79

80 Threads in C An error-handling module See mypthread.h See mypthread.c Spawning threads See spawning.c 80

81 Threads in C Joining threads See joining.c Locking See lockinuser.c See lockinresource.c Conditions See conditions.c 81

82 Threads in C Deadlock See deadlock.c See nodeadlock.c Interrupting (Not available in C) Inter-thread comm (Omitted) 82

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

Process Management! Goals of this Lecture!

Process Management! Goals of this Lecture! Process Management! 1 Goals of this Lecture! Help you learn about:" Creating new processes" Programmatically redirecting stdin, stdout, and stderr" (Appendix) communication between processes via pipes"

More information

Process Management 1

Process Management 1 Process Management 1 Goals of this Lecture Help you learn about: Creating new processes Programmatically redirecting stdin, stdout, and stderr (Appendix) communication between processes via pipes Why?

More information

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers 1 Critical sections and atomicity We have been seeing that sharing mutable objects between different threads is tricky We need some

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

Operating System Structure

Operating System Structure Operating System Structure CSCI 4061 Introduction to Operating Systems Applications Instructor: Abhishek Chandra Operating System Hardware 2 Questions Operating System Structure How does the OS manage

More information

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017 CS 471 Operating Systems Yue Cheng George Mason University Fall 2017 1 Review: Sync Terminology Worksheet 2 Review: Semaphores 3 Semaphores o Motivation: Avoid busy waiting by blocking a process execution

More information

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking

More information

Object Oriented Programming. Week 10 Part 1 Threads

Object Oriented Programming. Week 10 Part 1 Threads Object Oriented Programming Week 10 Part 1 Threads Lecture Concurrency, Multitasking, Process and Threads Thread Priority and State Java Multithreading Extending the Thread Class Defining a Class that

More information

What is a thread anyway?

What is a thread anyway? Concurrency in Java What is a thread anyway? Smallest sequence of instructions that can be managed independently by a scheduler There can be multiple threads within a process Threads can execute concurrently

More information

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

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a. Let s start writing programs that do more than one thing at at a. Threads, Concurrency,

More information

Chapter 4: Threads. Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads

Chapter 4: Threads. Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads Chapter 4: Threads Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads Chapter 4: Threads Objectives To introduce the notion of a

More information

Performance Throughput Utilization of system resources

Performance Throughput Utilization of system resources Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency

More information

Princeton University Computer Science 217: Introduction to Programming Systems Exceptions and Processes

Princeton University Computer Science 217: Introduction to Programming Systems Exceptions and Processes Princeton University Computer Science 217: Introduction to Programming Systems Exceptions and Processes Much of the material for this lecture is drawn from Computer Systems: A Programmer s Perspective

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, Concurrency, and Parallelism

Threads, Concurrency, and Parallelism Threads, Concurrency, and Parallelism Lecture 24 CS2110 Spring 2017 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a time. Let s start

More information

Processes. CS3026 Operating Systems Lecture 05

Processes. CS3026 Operating Systems Lecture 05 Processes CS3026 Operating Systems Lecture 05 Dispatcher Admit Ready Queue Dispatch Processor Release Timeout or Yield Event Occurs Blocked Queue Event Wait Implementation: Using one Ready and one Blocked

More information

CPS 310 first midterm exam, 10/6/2014

CPS 310 first midterm exam, 10/6/2014 CPS 310 first midterm exam, 10/6/2014 Your name please: Part 1. More fun with fork and exec* What is the output generated by this program? Please assume that each executed print statement completes, e.g.,

More information

Chapter 4: Threads. Operating System Concepts. Silberschatz, Galvin and Gagne

Chapter 4: Threads. Operating System Concepts. Silberschatz, Galvin and Gagne Chapter 4: Threads Silberschatz, Galvin and Gagne Chapter 4: Threads Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Linux Threads 4.2 Silberschatz, Galvin and

More information

fork System-Level Function

fork System-Level Function Princeton University Computer Science 217: Introduction to Programming Systems Process Management Goals of this Lecture Help you learn about: Creating new processes Waiting for processes to terminate Executing

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

Lecture 4: Process Management

Lecture 4: Process Management Lecture 4: Process Management (Chapters 2-3) Process: execution context of running program. A process does not equal a program! Process is an instance of a program Many copies of same program can be running

More information

Advanced Concepts of Programming

Advanced Concepts of Programming Berne University of Applied Sciences E. Benoist / E. Dubuis January 2005 1 Multithreading in Java Java provides the programmer with built-in threading capabilities The programmer can create and manipulate

More information

UNIT V CONCURRENT PROGRAMMING

UNIT V CONCURRENT PROGRAMMING UNIT V CONCURRENT PROGRAMMING Multi-Threading: Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such

More information

Getting to know you. Anatomy of a Process. Processes. Of Programs and Processes

Getting to know you. Anatomy of a Process. Processes. Of Programs and Processes Getting to know you Processes A process is an abstraction that supports running programs A sequential stream of execution in its own address space A process is NOT the same as a program! So, two parts

More information

Parallel Programming Languages COMP360

Parallel Programming Languages COMP360 Parallel Programming Languages COMP360 The way the processor industry is going, is to add more and more cores, but nobody knows how to program those things. I mean, two, yeah; four, not really; eight,

More information

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team http://101companies.org/wiki/ Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Non-101samples available here: https://github.com/101companies/101repo/tree/master/technologies/java_platform/samples/javathreadssamples

More information

Processes & Threads. Recap of the Last Class. Microkernel System Architecture. Layered Structure

Processes & Threads. Recap of the Last Class. Microkernel System Architecture. Layered Structure Recap of the Last Class Processes & Threads CS 256/456 Dept. of Computer Science, University of Rochester Hardware protection kernel and user mode System components process management, memory management,

More information

Processes and Exceptions

Processes and Exceptions Princeton University Computer Science 217: Introduction to Programming Systems Processes and Exceptions Much of the material for this lecture is drawn from Computer Systems: A Programmer s Perspective

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 4: Processes (2) Threads Process Creation: Unix In Unix, processes are created using fork() int fork() fork() Creates and initializes a new PCB Creates

More information

Java Threads. Introduction to Java Threads

Java Threads. Introduction to Java Threads Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent

More information

CMSC421: Principles of Operating Systems

CMSC421: Principles of Operating Systems CMSC421: Principles of Operating Systems Nilanjan Banerjee Assistant Professor, University of Maryland Baltimore County nilanb@umbc.edu http://www.csee.umbc.edu/~nilanb/teaching/421/ Principles of Operating

More information

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking Java Thread Multitasking Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking Allows programs (processes) to run concurrently

More information

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

OS Structure, Processes & Process Management. Don Porter Portions courtesy Emmett Witchel

OS Structure, Processes & Process Management. Don Porter Portions courtesy Emmett Witchel OS Structure, Processes & Process Management Don Porter Portions courtesy Emmett Witchel 1 What is a Process?! A process is a program during execution. Ø Program = static file (image) Ø Process = executing

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent

More information

CPS221 Lecture: Threads

CPS221 Lecture: Threads Objectives CPS221 Lecture: Threads 1. To introduce threads in the context of processes 2. To introduce UML Activity Diagrams last revised 9/5/12 Materials: 1. Diagram showing state of memory for a process

More information

CS 450 Operating System Week 4 Lecture Notes

CS 450 Operating System Week 4 Lecture Notes CS 450 Operating System Week 4 Lecture Notes Reading: Operating System Concepts (7 th Edition) - Silberschatz, Galvin, Gagne Chapter 5 - Pages 129 147 Objectives: 1. Explain the main Objective of Threads

More information

Threads and Java Memory Model

Threads and Java Memory Model Threads and Java Memory Model Oleg Šelajev @shelajev oleg@zeroturnaround.com October 6, 2014 Agenda Threads Basic synchronization Java Memory Model Concurrency Concurrency - several computations are executing

More information

Chapter 32 Multithreading and Parallel Programming

Chapter 32 Multithreading and Parallel Programming Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to

More information

What is a Process? Processes and Process Management Details for running a program

What is a Process? Processes and Process Management Details for running a program 1 What is a Process? Program to Process OS Structure, Processes & Process Management Don Porter Portions courtesy Emmett Witchel! A process is a program during execution. Ø Program = static file (image)

More information

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads? Objectives MultiThreading What are Threads? Interrupting threads Thread properties By Võ Văn Hải Faculty of Information Technologies Summer 2012 Threads priorities Synchronization Callables and Futures

More information

Introduction to Java Threads

Introduction to Java Threads Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The

More information

Princeton University Computer Science 217: Introduction to Programming Systems. Process Management

Princeton University Computer Science 217: Introduction to Programming Systems. Process Management Princeton University Computer Science 217: Introduction to Programming Systems Process Management 1 Goals of this Lecture Help you learn about: Creating new processes Waiting for processes to terminate

More information

Java Programming Lecture 23

Java Programming Lecture 23 Java Programming Lecture 23 Alice E. Fischer April 19, 2012 Alice E. Fischer () Java Programming - L23... 1/20 April 19, 2012 1 / 20 Outline 1 Thread Concepts Definition and Purpose 2 Java Threads Creation

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

Princeton University Computer Science 217: Introduction to Programming Systems. Process Management

Princeton University Computer Science 217: Introduction to Programming Systems. Process Management Princeton University Computer Science 217: Introduction to Programming Systems Process Management 1 Goals of this Lecture Help you learn about: Creating new processes Waiting for processes to terminate

More information

Lecture 2: February 6

Lecture 2: February 6 CMPSCI 691W Parallel and Concurrent Programming Spring 2006 Lecture 2: February 6 Lecturer: Emery Berger Scribe: Richard Chang 2.1 Overview This lecture gives an introduction to processes and threads.

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

Only one thread can own a specific monitor

Only one thread can own a specific monitor Java 5 Notes Threads inherit their priority and daemon properties from their creating threads The method thread.join() blocks and waits until the thread completes running A thread can have a name for identification

More information

Fall 2014:: CSE 506:: Section 2 (PhD) Threading. Nima Honarmand (Based on slides by Don Porter and Mike Ferdman)

Fall 2014:: CSE 506:: Section 2 (PhD) Threading. Nima Honarmand (Based on slides by Don Porter and Mike Ferdman) Threading Nima Honarmand (Based on slides by Don Porter and Mike Ferdman) Threading Review Multiple threads of execution in one address space Why? Exploits multiple processors Separate execution stream

More information

Introducing Shared-Memory Concurrency

Introducing Shared-Memory Concurrency Race Conditions and Atomic Blocks November 19, 2007 Why use concurrency? Communicating between threads Concurrency in Java/C Concurrency Computation where multiple things happen at the same time is inherently

More information

Princeton University. Computer Science 217: Introduction to Programming Systems. Process Management

Princeton University. Computer Science 217: Introduction to Programming Systems. Process Management Princeton University Computer Science 217: Introduction to Programming Systems Process Management 1 Goals of this Lecture Help you learn about: Creating new processes Waiting for processes to terminate

More information

Process Management 1

Process Management 1 Process Management 1 Goals of this Lecture Help you learn about: Creating new processes Waiting for processes to terminate Executing new programs Shell structure Why? Creating new processes and executing

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

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

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Need for synchronization: If threads comprise parts of our software systems, then they must communicate. Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.

More information

Threads. CS 475, Spring 2018 Concurrent & Distributed Systems

Threads. CS 475, Spring 2018 Concurrent & Distributed Systems Threads CS 475, Spring 2018 Concurrent & Distributed Systems Review: Signals OS has a mechanism to interrupt regular execution of a process We've discussed this in the context of preemption - when a round-robin

More information

Contents. 6-1 Copyright (c) N. Afshartous

Contents. 6-1 Copyright (c) N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004

More information

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

4/9/17. Memory sharing. Device sharing. Princeton University Computer Science 217: Introduction to Programming Systems.

4/9/17. Memory sharing. Device sharing. Princeton University Computer Science 217: Introduction to Programming Systems. Princeton University Computer Science 217: Introduction to Programming Systems sharing Just one CPU, but each appears to have its own CPU s and Processes 1 2 10 milliseconds Much of the material for this

More information

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems : Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either

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

Synchronization in Concurrent Programming. Amit Gupta

Synchronization in Concurrent Programming. Amit Gupta Synchronization in Concurrent Programming Amit Gupta Announcements Project 1 grades are out on blackboard. Detailed Grade sheets to be distributed after class. Project 2 grades should be out by next Thursday.

More information

Exceptions and Processes

Exceptions and Processes Exceptions and Processes Much of the material for this lecture is drawn from Computer Systems: A Programmer s Perspective (Bryant & O Hallaron) Chapter 8 1 Goals of this Lecture Help you learn about: Exceptions

More information

W4118 Operating Systems. Junfeng Yang

W4118 Operating Systems. Junfeng Yang W4118 Operating Systems Junfeng Yang What is a process? Outline Process dispatching Common process operations Inter-process Communication What is a process Program in execution virtual CPU Process: an

More information

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

CS 475. Process = Address space + one thread of control Concurrent program = multiple threads of control Processes & Threads Concurrent Programs Process = Address space + one thread of control Concurrent program = multiple threads of control Multiple single-threaded processes Multi-threaded process 2 1 Concurrent

More information

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

POSIX Threads: a first step toward parallel programming. George Bosilca POSIX Threads: a first step toward parallel programming George Bosilca bosilca@icl.utk.edu Process vs. Thread A process is a collection of virtual memory space, code, data, and system resources. A thread

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on

More information

Processes & Threads. Recap of the Last Class. Layered Structure. Virtual Machines. CS 256/456 Dept. of Computer Science, University of Rochester

Processes & Threads. Recap of the Last Class. Layered Structure. Virtual Machines. CS 256/456 Dept. of Computer Science, University of Rochester Recap of the Last Class Processes & Threads CS 256/456 Dept. of Computer Science, University of Rochester Hardware protection kernel and mode System components process management, memory management, I/O

More information

Operating Systems 2 nd semester 2016/2017. Chapter 4: Threads

Operating Systems 2 nd semester 2016/2017. Chapter 4: Threads Operating Systems 2 nd semester 2016/2017 Chapter 4: Threads Mohamed B. Abubaker Palestine Technical College Deir El-Balah Note: Adapted from the resources of textbox Operating System Concepts, 9 th edition

More information

Operating Systems. Review ENCE 360

Operating Systems. Review ENCE 360 Operating Systems Review ENCE 360 High level Concepts What are three conceptual pieces fundamental to operating systems? High level Concepts What are three conceptual pieces fundamental to operating systems?

More information

Threads Chate Patanothai

Threads Chate Patanothai Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?

More information

Concurrent and Real-Time Programming in Java

Concurrent and Real-Time Programming in Java 064202 Degree Examinations 2003 DEPARTMENT OF COMPUTER SCIENCE Concurrent and Real-Time Programming in Java Time allowed: One and one half (1.5) hours Candidates should answer not more than two questions.

More information

Process Management! Goals of this Lecture!

Process Management! Goals of this Lecture! Process Management! 1 Goals of this Lecture! Help you learn about:" Creating new processes" Programmatically redirecting stdin, stdout, and stderr" Unix system-level functions for I/O" The Unix stream

More information

ECE 550D Fundamentals of Computer Systems and Engineering. Fall 2017

ECE 550D Fundamentals of Computer Systems and Engineering. Fall 2017 ECE 550D Fundamentals of Computer Systems and Engineering Fall 2017 The Operating System (OS) Prof. John Board Duke University Slides are derived from work by Profs. Tyler Bletsch and Andrew Hilton (Duke)

More information

COSC243 Part 2: Operating Systems

COSC243 Part 2: Operating Systems COSC243 Part 2: Operating Systems Lecture 16: Threads and data sharing Zhiyi Huang Dept. of Computer Science, University of Otago Zhiyi Huang (Otago) COSC243 Lecture 16 1 / 24 Overview Last lecture: Hierarchical

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Multithreading Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to large compute clusters Can perform multiple

More information

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico. Java Monitors Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico October 19, 2010 Monteiro, Costa (DEI / IST) Parallel and Distributed Computing

More information

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files ... and systems programming C basic syntax functions arrays structs

More information

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs.

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs. CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files... and systems programming C basic syntax functions arrays structs

More information

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

CS 5523 Operating Systems: Midterm II - reivew Instructor: Dr. Tongping Liu Department Computer Science The University of Texas at San Antonio CS 5523 Operating Systems: Midterm II - reivew Instructor: Dr. Tongping Liu Department Computer Science The University of Texas at San Antonio Fall 2017 1 Outline Inter-Process Communication (20) Threads

More information

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks

More information

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 13 Robert Grimm, New York University 1 Review Last week Exceptions 2 Outline Concurrency Discussion of Final Sources for today s lecture: PLP, 12

More information

CMSC 132: Object-Oriented Programming II. Threads in Java

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

Animation Part 2: MoveableShape interface & Multithreading

Animation Part 2: MoveableShape interface & Multithreading Animation Part 2: MoveableShape interface & Multithreading MoveableShape Interface In the previous example, an image was drawn, then redrawn in another location Since the actions described above can apply

More information

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright MultiThreading Object Orientated Programming in Java Benjamin Kenwright Outline Review Essential Java Multithreading Examples Today s Practical Review/Discussion Question Does the following code compile?

More information

CS11 Java. Fall Lecture 7

CS11 Java. Fall Lecture 7 CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)

More information

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

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

Module - 4 Multi-Threaded Programming

Module - 4 Multi-Threaded Programming Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is

More information

Motivation of Threads. Preview. Motivation of Threads. Motivation of Threads. Motivation of Threads. Motivation of Threads 9/12/2018.

Motivation of Threads. Preview. Motivation of Threads. Motivation of Threads. Motivation of Threads. Motivation of Threads 9/12/2018. Preview Motivation of Thread Thread Implementation User s space Kernel s space Inter-Process Communication Race Condition Mutual Exclusion Solutions with Busy Waiting Disabling Interrupt Lock Variable

More information

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Operating Systems Lecture 4 - Concurrency and Synchronization Adrien Krähenbühl Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Mutual exclusion Hardware solutions Semaphores IPC: Message passing

More information

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY Instructors: Crista Lopes Copyright Instructors. Basics Concurrent Programming More than one thing at a time Examples: Network server handling hundreds of clients

More information

Process Concepts. CSC400 - Operating Systems. 3. Process Concepts. J. Sumey

Process Concepts. CSC400 - Operating Systems. 3. Process Concepts. J. Sumey CSC400 - Operating Systems 3. Process Concepts J. Sumey Overview Concurrency Processes & Process States Process Accounting Interrupts & Interrupt Processing Interprocess Communication CSC400 - Process

More information

Basics of. Multithreading in Java

Basics of. Multithreading in Java Basics of programming 3 Multithreading in Java Thread basics Motivation in most cases sequential (single threaded) applications are not adequate it s easier to decompose tasks into separate instruction

More information