Shared-Memory and Multithread Programming

Size: px
Start display at page:

Download "Shared-Memory and Multithread Programming"

Transcription

1 Shared-Memory and Multithread Programming Pruet Boonma Department of Computer Engineering Faculty of Engineering, Chiang Mai University Based on a material by: Bryan Carpenter Pervasive Technology Labs Indiana University

2 In this week. 2 Shared Memory Parallel Computing with Java Threads Mutual Exclusion. Synchronization between Java Threads using wait() and notify(). Other features of Java Threads.

3 Threaded programming and Threaded Language 3 Thread is a way to do parallel computing. In C, C++, etc it is possible to do multithreaded programming, given a suitable library. e.g. the pthreads library Thread libraries provide one approach to doing parallel programming on computers with shared memory. Unlike these (traditional HPC) languages, Java integrates threads into the basic language specification in a much tighter way. Every Java Virtual Machine must support threads. Although this close integration doesn t exactly make multithreaded programming in Java easy, it does help avoid common programming errors, and keeps the semantics clean.

4 Features of Java Threads 4 Java provides a set of synchronization primitives based on monitor and condition variable paradigm of C.A.R. Hoare. Underlying functionality is similar to POSIX threads, for example. Syntactic extension for threads is (deceptively?) small: synchronized attribute on methods. synchronized statement. volatile keyword. Other thread management and synchronization captured in the Thread class and related classes. But the presence of threads has a more wide-ranging effect on the language specification and JVM implementation. e.g., the Java memory model.

5 Creating New Threads 5 Any Java thread of execution is associated with an instance of the Thread class. Before starting a new thread, you must create a new instance of this class. The Java Thread class implements the interface Runnable. So every Thread instance has a method: public void run() {... When the thread is started, the code executed in the new thread is the body of the run() method. Generally speaking the new thread ends when this method returns.

6 Making Thread Instances 6 There are two ways to create a thread instance (and define the thread run() method). Choose at your convenience: 1. Extend the Thread class and override the run() method, e.g.: class MyThread extends Thread { public void run() { System.out.println( Hello from another thread ) ;... Thread thread = new MyThread() ; 2. Create a separate Runnable object and pass it to the Thread constructor, e.g.: class MyRunnable implements Runnable { public void run() { System.out.println( Hello from another thread ) ;... Thread thread = new MyThread(new MyRunnable()) ;

7 Starting a Thread 7 Creating the Thread instance does not in itself start the thread running. To do that you must call the start() method on the new instance: thread.start() ; This operation causes the run() method to start executing concurrently with the original thread. In our example the new thread will print the message Hello from another thread to standard output, then immediately terminate. You can only call the start() method once on any Thread instance. Trying to restart a thread causes an exception to be thrown.

8 8 Example: Multiple Threads class MyThread extends Thread { MyThread(int id) { this.id = id ; public void run() { System.out.println( Hello from thread + id) ; private int id ;... Thread [] threads = new Thread [p] ; for(int i = 0 ; i < p ; i++) threads [i] = new MyThread(i) ; for(int i = 0 ; i < p ; i++) threads [i].start() ;

9 Remarks 9 This is one way of creating and starting p new threads to run concurrently. The output might be something like (for p = 4): Hello from thread 3 Hello from thread 4 Hello from thread 2 Hello from thread 1 Of course there is no guarantee of order (or atomicity) of outputs, because the threads are concurrent.

10 Mutual Exclusion

11 Avoiding Interference 11 In any non-trivial multithreaded (or shared-memory-parallel) program, interference between threads is an issue. Generally interference (or a race condition) occurs if two threads are trying to do operations on the same variables at the same time. This often results in corrupt data. But not always. It depends on the exact interleaving of instructions. This non-determinism is the worst feature of race conditions. A popular solution is to provide some kind of lock primitive. Only one thread can acquire a particular lock at any particular time. The concurrent program can then be written so that operations on a given group of variables are only ever performed by threads that hold the lock associated with that group. In POSIX threads, for example, the lock objects are called mutexes.

12 pthread_mutex_lock(&my_mutex) ; 12 Example use of a Mutex (in C) Thread A Thread B /* critical region */ tmp1 = count ; count = tmp1 + 1 ; pthread_mutex_unlock(&my_mutex) ; pthread_mutex_lock(&my_mutex) ; Blocked /* critical region */ tmp2 = count ; count = tmp2-1 ; pthread_mutex_unlock(&my_mutex) ;

13 Pthreads-style mutexes 13 In POSIX threads, a mutex is allocated then initialized with pthread_mutex_init(). Once a mutex is initialized, a thread can acquire a lock on it by calling e.g. pthread_mutex_lock(). While it holds the lock it performs some update on the variables guarded by the lock (critical region). Then the thread calls pthread_mutex_unlock() to release the lock. Other threads that try to call pthread_mutex_lock() while the critical region is being executed are blocked until the first thread releases the lock. This is fine, but opportunities for error include: There is no built-in association between the lock object (mutex) and the set of variables it guards it is up to the program to maintain a consistent association. If you forget to call pthread_mutex_unlock() after pthread_mutex_lock(), deadlocks will occur.

14 Monitors 14 Java addresses these problems by adopting a version of the monitors proposed by C.A.R. Hoare. Every Java object is created with its own lock (and every lock is associated with an object there is no way to create an isolated mutex). In Java this lock is often called the monitor lock. Methods of a class can be declared to be synchronized.

15 Monitors 15 The object s lock is acquired on entry to a synchronized method, and released on exit from the method. Synchronized static methods need slightly different treatment. Assuming methods generally modify the fields (instance variables) of the objects they are called on, this leads to a natural and systematic association between locks and the variables they guard: viz. a lock guards the instance variables of the object it is attached to. The critical region becomes the body of the synchronized method.

16 16 Example use of Synchronized Methods Thread A call to counter.increment() Thread B // body of synchronized method tmp1 = count ; count = tmp1 + 1 ; counter.increment() returns call to counter.decrement() Blocked // body of synchronized method tmp2 = count ; count = tmp2-1 ; counter.decrement() returns

17 Caveats 17 This approach helps to encourage good practices, and make multithreaded Java programs less error-prone than, say, multithreaded C programs. But it isn t magic: It still depends on correct identification of the critical regions, to avoid race conditions. The natural association between the lock of the object and its fields relies on the programmer following conventional patterns of object oriented programming (which the language encourages but doesn t enforce). By using the synchronized construct (see later), programs can break this association altogether. There are plenty more insidious ways to introduce deadlocks, besides accidentally forgetting to release a lock! Concurrent programming is hard, and if you start with the assumption Java somehow makes concurrent programming easy, you are probably going to write some broken programs!

18 18 Example: A Simple Queue public class SimpleQueue { private Node front, back ; public synchronized void add(object data) { if (front!= null) { back.next = new Node(data) ; back = back.next ; else { front = new Node(data) ; back = front ; public synchronized Object rem() { Object result = null ; if (front!= null) { result = front.data ; front = front.next ; return result ;

19 Remarks 19 This queue is implemented as a linked list with a front pointer and a back pointer. The method add() adds a node to the back of the list; the method rem() removes a node from the front of the list. The Node class just has a data field (type Object) and a next field (type Node). The rem() method immediately returns null when the queue is empty. The following slide gives an example of what could go wrong without mutual exclusion. It assumes two threads concurrently add nodes to the queue. In the initial state, Z is the last item in the queue. In the final state, the X node is orphaned, and the back pointer is null.

20 Thread A: add(x) The Need for Synchronized Methods Z null 20 back.next = new Node(X) ; back Thread B: add(y) Z X null back.next = new Node(Y) ; back = back.next ; back Z back X Y null null X null Z back Y null X null back = back.next ; Z Y null Corrupt data structure! back null

21 21 The synchronized construct The keyword synchronized also appears in the synchronized statement, which has syntax like: synchronized (object) { critical region Here object is a reference to any object. The synchronized statement first acquires the lock on this object, then executes the critical region, then releases the lock. Typically you might use this for the lock object, somewhere inside a nonesynchronized method, when the critical region is smaller than the whole method body. In general, though, the synchronized statement allows you to use the lock in any object to guard any code.

22 General Synchronization

23 23 Beyond Mutual Exclusion The mutual exclusion provided by synchronized methods and statements is an important special sort of synchronization. But there are other interesting forms of synchronization between threads. Mutual exclusion by itself is not enough to implement these more general sorts of thread interaction (not efficiently, at least). POSIX threads, for example, provides a second kind of synchronization object called a condition variable to implement more general inter-thread synchronization. In Java, condition variables (like locks) are implicit in the definition of objects: every object effectively has a single condition variable associated with it.

24 A Motivating Example 24 Consider the simple queue from the previous example. If we try to remove an item from the front of the queue when the queue is empty, SimpleQueue was specified to just return null. This is reasonable if our queue is just meant as a data structure buried somewhere in an algorithm. But what if the queue is a message buffer in a communication system? In that case, if the queue is empty, it may be more natural for the remove operation to block until some other thread added a message to the queue.

25 Busy Waiting 25 One approach would be to add a method that polls the queue until data is ready: public synchronized Object get() { while(true) { Object result = rem() ; if (result!= null) return result ; This works, but it may be inefficient to keep doing the basic rem() operation in a tight loop, if these machine cycles could be used by other threads. This isn t clear cut: sometimes busy waiting is the most efficient approach. Another possibility is to put a sleep() operation in the loop, to deschedule the thread for some fixed interval between polling operations. But then we lose responsiveness.

26 wait() and notify() 26 In general a more elegant approach is to use the wait() and notify() family of methods. These are defined in the Java Object class. Typically a call to a wait() method puts the calling thread to sleep until another thread wakes it up again by calling a notify() method. In our example, if the queue is currently empty, the get() method would invoke wait(). This causes the get() operation to block. Later when another thread calls add(), putting data on the queue, the add() method invokes notify() to wake up the sleeping thread. The get() method can then return.

27 A Simplified Example 27 public class Semaphore { int s ; public Semaphore(int s) { this.s = s ; public synchronized void add() { s++ ; notify() ; public synchronized void get() throws InterruptedException { while(s == 0) wait() ; s-- ;

28 Remarks I 28 Rather than a linked list we have a simple counter, which is required always to be non-negative. add() increments the counter. get() decrements the counter, but if the counter was zero it blocks until another thread increments the counter. The data structures are simplified, but the synchronization features used here are essentially identical to what would be needed in a blocking queue (left as an exercise). You may recognize this as an implementation of a classical semaphore an important synchronization primitive in its own right.

29 Remarks II 29 wait() and notify() must be used inside synchronized methods of the object they are applied to. The wait() operation pauses the thread that calls it. It also releases the lock which the thread holds on the object (for the duration of the wait() call: the lock will be claimed again before continuing, after the pause). Several threads can wait() simultaneously on the same object. If any threads are waiting on an object, the notify() method wakes up exactly one of those threads. If no threads are waiting on the object, notify() does nothing. A wait() method may throw an InterruptedException (rethrown by by get() in the example). This will be discussed later. Although the logic in the example doesn t strictly require it, universal lore has it that one should always put a wait() call in a loop, in case the condition that caused the thread to sleep has not been resolved when the wait() returns (a programmer flaunting this rule might use if in place of while).

30 Another Example 30 public class Barrier { private int n, generation = 0, count = 0 ; public Barrier(int n) { this.n = n ; public synchronized void synch() throws InterruptedException { int gennum = generation ; count++ ; if(count == n) { count = 0 ; generation++ ; notifyall() ; else while(generation == gennum) wait() ;

31 Remarks 31 This class implements barrier synchronization an important operation in shared memory parallel programming. It synchronizes n processes: when n threads make calls to synch() the first n-1 block until the last one has entered the barrier. The method notifyall() generalizes notify(). It wakes up all threads currently waiting on this object. Many authorities consider use of notifyall() to be safer than notify(), and recommend always to use notifyall(). In the example, the generation number labels the current, collective barrier operation: it is only really needed to control the while loop round wait(). And this loop is only really needed to conform to the standard pattern of wait()- usage, mentioned earlier.

32 Concluding Remarks on Synchronization 32 We illustrated with a couple of simple examples that wait() and notify() allow various interesting patterns of thread synchronization (or thread communication) to be implemented. In some sense these primitives are sufficient to implement general concurrent programming any pattern of thread synchronization can be implemented in terms of these primitives. For example you can easily implement message passing between threads (left as an exercise ) This doesn t mean these are necessarily the last word in synchronization: e.g. for scalable parallel processing one would like a primitive barrier operation more efficient than the O(n) implementation given above.

33 Other Features of Java Threads

34 Join Operations 34 The Thread API has a family of join() operations. These implement another simple but useful form of synchronization, by which the current thread can simply wait for another thread to terminate, e.g.: Thread child = new MyThread() ; child.start() ; Do something in current thread child.join() ; // wait for child thread to finish

35 Priority and Name 35 Thread have properties priority and name, which can be defined by suitable setter methods, before starting the thread, and accessed by getter methods.

36 Sleeping 36 You can cause a thread to sleep for a fixed interval using the sleep() methods. This operation is distinct from and less powerful than wait(). It is not possible for another thread to prematurely wake up a thread paused using sleep(). If you want to sleep for a fixed interval, but allow another thread to wake you beforehand if necessary, use the variants of wait() with timeouts instead.

37 Interrupting Threads 37 Calling the method interrupt() on a thread instance requests cancellation of the thread execution. It does this in an advisory way: the code for the interrupted thread must be written to explicitly test whether it has been interrupted, e.g.: public void run() { while(!interrupted()) do something Here interrupted() is a static method of the Thread class which determines whether the current thread has been interrupted If the interrupted thread is executing a blocking operation like wait() or sleep(), the operation may end with an InterruptedException. An interruptible thread should catch this exception and terminate itself. Clearly this mechanism depends wholly on suitable implementation of the thread body. The programmer must decide at the outset whether it is important that a particular thread be responsive to interrupts often it isn t.

38 Thread-based Parallel Applications and Benchmarks

39 39 Threads on Symmetric Multiprocessors Most modern implementations of the Java Virtual Machine will map Java threads into native threads of the underlying operating system. For example these may be POSIX threads. On multiprocessor architectures with shared memory, these threads can exploit multiple available processors. Hence it is possible to do true parallel programming using Java threads within a single JVM.

40 40 Select Application Benchmark Results We present some results, borrowed from the literature in this area. Two codes are described in High-Performance Java Codes for Computational Fluid Dynamics C. Riley, S. Chatterjee, and R. Biswas, ACM 2001 Java Grande/ISCOPE LAURA is a finite-volume flow solver for multiblock, structured grids.

41 41 Parallel Speedup of LAURA Code

42 Remarks 42 LAURA speedups are generally fair, and are outstanding with the Jalapeno JVM on PowerPC (unfortunately this is the only JVM that isn t freely available.) LAURA is regular, and the parallelization strategy needs little or no locking.

43 43 HW: Java Thread Synchronization Following the pattern of the Semaphore class, complete the implementation of a queue with a get() operation that blocks when the queue is empty, using wait() and notify(). Extend this to implement send() and recv() primitives for communicating between threads by message-passing. Try implementing other features of the MPI standard for communication between threads, e.g. synchronous mode sends (where both sender and receive block until both are ready to communicate). Avoid busy-waiting or polling solutions.

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

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

Threads and Parallelism in Java

Threads and Parallelism in Java Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program

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

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

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

Multiple Inheritance. Computer object can be viewed as

Multiple Inheritance. Computer object can be viewed as Multiple Inheritance We have seen that a class may be derived from a given parent class. It is sometimes useful to allow a class to be derived from more than one parent, inheriting members of all parents.

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

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

Synchronization in Java

Synchronization in Java Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park Synchronization Overview Unsufficient atomicity Data races Locks Deadlock Wait /

More information

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data Lecture 4 Monitors Summary Semaphores Good news Simple, efficient, expressive Passing the Baton any await statement Bad news Low level, unstructured omit a V: deadlock omit a P: failure of mutex Synchronisation

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

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

Java Threads. Written by John Bell for CS 342, Spring 2018

Java Threads. Written by John Bell for CS 342, Spring 2018 Java Threads Written by John Bell for CS 342, Spring 2018 Based on chapter 9 of Learning Java, Fourth Edition by Niemeyer and Leuck, and other sources. Processes A process is an instance of a running program.

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

Concurrent Programming

Concurrent Programming Concurrency Concurrent Programming A sequential program has a single thread of control. Its execution is called a process. A concurrent program has multiple threads of control. They may be executed as

More information

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst Operating Systems CMPSCI 377 Spring 2017 Mark Corner University of Massachusetts Amherst What is a Monitor? Ties data and the synchronization operations together Monitors guarantee mutual exclusion, i.e.,

More information

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger COMP31212: Concurrency A Review of Java Concurrency Giles Reger Outline What are Java Threads? In Java, concurrency is achieved by Threads A Java Thread object is just an object on the heap, like any other

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

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

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

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

Reintroduction to Concurrency

Reintroduction to Concurrency Reintroduction to Concurrency The execution of a concurrent program consists of multiple processes active at the same time. 9/25/14 7 Dining philosophers problem Each philosopher spends some time thinking

More information

Lecture 8: September 30

Lecture 8: September 30 CMPSCI 377 Operating Systems Fall 2013 Lecture 8: September 30 Lecturer: Prashant Shenoy Scribe: Armand Halbert 8.1 Semaphores A semaphore is a more generalized form of a lock that can be used to regulate

More information

Java s Implementation of Concurrency, and how to use it in our applications.

Java s Implementation of Concurrency, and how to use it in our applications. Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video

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

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

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

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

Concurrency in Java Prof. Stephen A. Edwards

Concurrency in Java Prof. Stephen A. Edwards Concurrency in Java Prof. Stephen A. Edwards The Java Language Developed by James Gosling et al. at Sun Microsystems in the early 1990s Originally called Oak, first intended application was as an OS for

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

Synchronization synchronization.

Synchronization synchronization. Unit 4 Synchronization of threads using Synchronized keyword and lock method- Thread pool and Executors framework, Futures and callable, Fork-Join in Java. Deadlock conditions 1 Synchronization When two

More information

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Threads block when they can t get that lock Wanna have your threads stall? Go ahead, synchronize it all The antidote to this liveness pitfall? Keeping

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

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

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

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

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

Monitors; Software Transactional Memory

Monitors; Software Transactional Memory Monitors; Software Transactional Memory Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico March 17, 2016 CPD (DEI / IST) Parallel and Distributed

More information

Concurrent Programming using Threads

Concurrent Programming using Threads Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object

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

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

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

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy Operating Systems Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. AL-AZHAR University Website : eaymanelshenawy.wordpress.com Email : eaymanelshenawy@yahoo.com Reference

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

Info 408 Distributed Applications programming 2 nd semester of 2017/2018 Credits: 5 Lecturer: Dr. Antoun Yaacoub

Info 408 Distributed Applications programming 2 nd semester of 2017/2018 Credits: 5 Lecturer: Dr. Antoun Yaacoub Lebanese University Faculty of Sciences I Master 1 degree Computer Sciences Info 408 Distributed Applications programming 2 nd semester of 2017/2018 Credits: 5 Lecturer: Dr. Antoun Yaacoub 2 Multithreading

More information

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems Synchronization CS 475, Spring 2018 Concurrent & Distributed Systems Review: Threads: Memory View code heap data files code heap data files stack stack stack stack m1 m1 a1 b1 m2 m2 a2 b2 m3 m3 a3 m4 m4

More information

Java Threads and intrinsic locks

Java Threads and intrinsic locks Java Threads and intrinsic locks 1. Java and OOP background fundamentals 1.1. Objects, methods and data One significant advantage of OOP (object oriented programming) is data encapsulation. Each object

More information

What's wrong with Semaphores?

What's wrong with Semaphores? Next: Monitors and Condition Variables What is wrong with semaphores? Monitors What are they? How do we implement monitors? Two types of monitors: Mesa and Hoare Compare semaphore and monitors Lecture

More information

Info 408 Distributed Applications Programming Exercise sheet nb. 4

Info 408 Distributed Applications Programming Exercise sheet nb. 4 Lebanese University Info 408 Faculty of Science 2017-2018 Section I 1 Custom Connections Info 408 Distributed Applications Programming Exercise sheet nb. 4 When accessing a server represented by an RMI

More information

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 Topics: Threading, Synchronization 1 Threading Suppose we want to create an automated program that hacks into a server. Many encryption

More information

1 Process Coordination

1 Process Coordination COMP 730 (242) Class Notes Section 5: Process Coordination 1 Process Coordination Process coordination consists of synchronization and mutual exclusion, which were discussed earlier. We will now study

More information

CS510 Advanced Topics in Concurrency. Jonathan Walpole

CS510 Advanced Topics in Concurrency. Jonathan Walpole CS510 Advanced Topics in Concurrency Jonathan Walpole Threads Cannot Be Implemented as a Library Reasoning About Programs What are the valid outcomes for this program? Is it valid for both r1 and r2 to

More information

Multithreaded Programming

Multithreaded Programming Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes

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

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

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar JAVA CONCURRENCY FRAMEWORK Kaushik Kanetkar Old days One CPU, executing one single program at a time No overlap of work/processes Lots of slack time CPU not completely utilized What is Concurrency Concurrency

More information

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006 This document provides a brief introduction to programming with threads in Java. I presume familiarity

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

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

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Week 7 Concurrent Programming: Thread Synchronization CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2 Outcomes Understand

More information

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010 CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion Tyler Robison Summer 2010 1 Toward sharing resources (memory) So far we ve looked at parallel algorithms using fork-join

More information

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition Module 6: Process Synchronization 6.1 Silberschatz, Galvin and Gagne 2009 Module 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores

More information

The New Java Technology Memory Model

The New Java Technology Memory Model The New Java Technology Memory Model java.sun.com/javaone/sf Jeremy Manson and William Pugh http://www.cs.umd.edu/~pugh 1 Audience Assume you are familiar with basics of Java technology-based threads (

More information

CS Operating Systems

CS Operating Systems CS 4500 - Operating Systems Module 4: The Producer-Consumer Problem and Solution Methods Stanley Wileman Department of Computer Science University of Nebraska at Omaha Omaha, NE 68182-0500, USA June 3,

More information

CS Operating Systems

CS Operating Systems CS 4500 - Operating Systems Module 4: The Producer-Consumer Problem and Solution Methods Stanley Wileman Department of Computer Science University of Nebraska at Omaha Omaha, NE 68182-0500, USA June 3,

More information

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;

More information

Threading and Synchronization. Fahd Albinali

Threading and Synchronization. Fahd Albinali Threading and Synchronization Fahd Albinali Parallelism Parallelism and Pseudoparallelism Why parallelize? Finding parallelism Advantages: better load balancing, better scalability Disadvantages: process/thread

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

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

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

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

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running

More information

Reminder from last time

Reminder from last time Concurrent systems Lecture 3: CCR, monitors, and concurrency in practice DrRobert N. M. Watson 1 Reminder from last time Implementing mutual exclusion: hardware support for atomicity and inter-processor

More information

Process Management And Synchronization

Process Management And Synchronization Process Management And Synchronization In a single processor multiprogramming system the processor switches between the various jobs until to finish the execution of all jobs. These jobs will share the

More information

Last Class: Synchronization

Last Class: Synchronization Last Class: Synchronization Synchronization primitives are required to ensure that only one thread executes in a critical section at a time. Concurrent programs Low-level atomic operations (hardware) load/store

More information

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads Concurrency - Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads 1 Introduction Concurrency can occur at four levels: Machine instruction

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

Synchronization COMPSCI 386

Synchronization COMPSCI 386 Synchronization COMPSCI 386 Obvious? // push an item onto the stack while (top == SIZE) ; stack[top++] = item; // pop an item off the stack while (top == 0) ; item = stack[top--]; PRODUCER CONSUMER Suppose

More information

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T Operating Systems Operating Systems Summer 2017 Sina Meraji U of T More Special Instructions Swap (or Exchange) instruction Operates on two words atomically Can also be used to solve critical section problem

More information

Last Class: Synchronization. Review. Semaphores. Today: Semaphores. MLFQ CPU scheduler. What is test & set?

Last Class: Synchronization. Review. Semaphores. Today: Semaphores. MLFQ CPU scheduler. What is test & set? Last Class: Synchronization Review Synchronization Mutual exclusion Critical sections Example: Too Much Milk Locks Synchronization primitives are required to ensure that only one thread executes in a critical

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

CS 159: Parallel Processing

CS 159: Parallel Processing Outline: Concurrency using Java CS 159: Parallel Processing Spring 2007 Processes vs Threads Thread basics Synchronization Locks Examples Avoiding problems Immutable objects Atomic operations High"level

More information

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs CSE 451: Operating Systems Winter 2005 Lecture 7 Synchronization Steve Gribble Synchronization Threads cooperate in multithreaded programs to share resources, access shared data structures e.g., threads

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

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

Pre-lab #2 tutorial. ECE 254 Operating Systems and Systems Programming. May 24, 2012 Pre-lab #2 tutorial ECE 254 Operating Systems and Systems Programming May 24, 2012 Content Concurrency Concurrent Programming Thread vs. Process POSIX Threads Synchronization and Critical Sections Mutexes

More information

Concurrency and Synchronisation

Concurrency and Synchronisation Concurrency and Synchronisation 1 Learning Outcomes Understand concurrency is an issue in operating systems and multithreaded applications Know the concept of a critical region. Understand how mutual exclusion

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

Problems with Concurrency. February 19, 2014

Problems with Concurrency. February 19, 2014 with Concurrency February 19, 2014 s with concurrency interleavings race conditions dead GUI source of s non-determinism deterministic execution model 2 / 30 General ideas Shared variable Access interleavings

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

Chapter 6 Process Synchronization

Chapter 6 Process Synchronization Chapter 6 Process Synchronization Cooperating Process process that can affect or be affected by other processes directly share a logical address space (threads) be allowed to share data via files or messages

More information

Problem Set 2. CS347: Operating Systems

Problem Set 2. CS347: Operating Systems CS347: Operating Systems Problem Set 2 1. Consider a clinic with one doctor and a very large waiting room (of infinite capacity). Any patient entering the clinic will wait in the waiting room until the

More information

CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion. Ruth Anderson Winter 2019

CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion. Ruth Anderson Winter 2019 CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion Ruth Anderson Winter 2019 Toward sharing resources (memory) So far, we have been studying parallel algorithms

More information

Faculty of Computers & Information Computer Science Department

Faculty of Computers & Information Computer Science Department Cairo University Faculty of Computers & Information Computer Science Department Theoretical Part 1. Introduction to Critical Section Problem Critical section is a segment of code, in which the process

More information

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 Lecture 9: Readers-Writers and Language Support for Synchronization 9.1.2 Constraints 1. Readers can access database

More information

Models of concurrency & synchronization algorithms

Models of concurrency & synchronization algorithms Models of concurrency & synchronization algorithms Lecture 3 of TDA383/DIT390 (Concurrent Programming) Carlo A. Furia Chalmers University of Technology University of Gothenburg SP3 2016/2017 Today s menu

More information

Concurrent Processes Rab Nawaz Jadoon

Concurrent Processes Rab Nawaz Jadoon Concurrent Processes Rab Nawaz Jadoon DCS COMSATS Institute of Information Technology Assistant Professor COMSATS Lahore Pakistan Operating System Concepts Concurrent Processes If more than one threads

More information

Exercises and Labs. Part I. Exercises

Exercises and Labs. Part I. Exercises Exercises and Labs Part I Exercises 7 Exercises and Labs Exercise 1 Semaphores Answer the questions below: 1. Sometimes, multiple threads in a program write to the same file concurrently. One example

More information

1. Introduction to Concurrent Programming

1. Introduction to Concurrent Programming 1. Introduction to Concurrent Programming A concurrent program contains two or more threads that execute concurrently and work together to perform some task. When a program is executed, the operating system

More information

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018 Deadlock and Monitors CS439: Principles of Computer Systems September 24, 2018 Bringing It All Together Processes Abstraction for protection Define address space Threads Share (and communicate) through

More information