# re-exam Concurrent Programming tda383/dit390 Date: Time: 14:00 18:00 Place: Maskinhuset (M)

Save this PDF as:

Size: px
Start display at page:

## Transcription

4 Part 2: State spaces (16p) The algorithm below attempts to solve the critical section problem, and is built from atomic if statements (p4 and q4) and atomic await statements (p3 and q3). The test of the condition following if, and the corresponding then or else action, are both carried out in one step, which the other process cannot interrupt. Similarly, the test of the condition following await and the corresponding action are carried in one step. The then actions of p4 and q4 contain an assignment and a break statement, whose execution terminates the execution of the innermost loop the one starting in p2 or q2 in this case. integer T := 0 p0 loop forever p1 non-critical section p2 loop forever p3 await (T == 0 T == 2) T := T + 1; p4 if T == 3 then T := 4; break else skip p5 T := 2 p6 critical section p7 T := 0 q0 loop forever q1 non-critical section q2 loop forever q3 await (T == 0 T == 2) T := T + 1; q4 if T == 1 then T := 5; break else skip q5 T := 0 q6 critical section q7 T := 2 Below is part of the state transition table for an abbreviated version of this program, skipping p1, p6, q1 and q6 (the critical and non-critical sections), as well as p0, q0, p2 and q2. For example, in line 3 of the table below q4 transitions directly to q7 after breaking of from the loop, skipping q6. A state transition table is a tabular version of a state diagram. The left-hand column lists the states. The middle column gives the next state if p next executes a step, and the right-hand column gives the next state if q next executes a step. In many states both p or q are free to execute the next step, and either may do so. But in some states, such as 2, 3 or 10 below, one or other of the processes may be blocked. There are 10 states in total. 4

5 State = (pi, qi, T) next state if p moves next state if q moves 1 (p3, q3, 0) (p4, q3, 1) (p3, q4, 1) 2 (p4, q3, 1) (p5, q3, 1) no move 3 (p3, q4, 1) no move (p3, q7, 5) 4??? 5??? 6??? 7??? 8??? 9??? 10 (p3, q5, 3) no move (p3, q3, 0) Complete the state transition table (correctness of the table will not be assessed). Are the following states reachable in the algorithm above? (1p) 2.1. (p7, q3, 5) (A) Yes (B) No (1p) 2.2. (p3, q3, 3) (A) Yes (B) No (1p) 2.3. (p3, q3, 2) (A) Yes (B) No (1p) 2.4. (p3, q4, 3) (A) Yes (B) No (1p) 2.5. (p3, q5, 4) (A) Yes (B) No (3p) 2.6. Prove from your state transition table that the program ensures mutual exclusion. Do the following invariants hold? The notation p3, p4, p5, etc. denotes the condition that process p is currently executing line 3, 4, 5, etc. (1p) 2.7. pp3 ^ q3q Ñ pt 5 _ T 7q (A) Yes (B) No (1p) 2.8. p7 Ñ T 4 (A) Yes (B) No (1p) 2.9. p4 Ñ pt 1 _ T 2q (A) Yes (B) No (1p) q3 Ñ pt 0 _ T 2q (A) Yes (B) No (4p) Is the solution presented above free from deadlock? Present a proof that it is the case or give a counterexample. 5

6 Part 3: Concurrent Java i (16p) The following code merges two streams of non-negative integers by adding them. It uses an implementation of a thread-safe bounded buffer BBuffer (implementation omitted) that supports the standard operations get and put. In addition, BBuffer can also report its maximum capacity (which is set in the constructor) using the capacity() method and the current number of elements it holds using the size() method. The imports have been omitted for clarity. 1 import java.util.concurrent.locks.*; 2 3 class Merge { 4 static class BBuffer { 5 public BBuffer(int size) {...} 6 public void put(int t) throws InterruptedException {...} 7 public int get() throws InterruptedException {...} 8 public int capacity() {...} 9 public int size() throws InterruptedException {...} 10 } // Two queues that are merged 13 BBuffer buf1 = new BBuffer(5); 14 BBuffer buf2 = new BBuffer(5); 15 // Total numbers of added and removed elements 16 int buf1total = 0; 17 int buf2total = 0; 18 int gettotal = 0; 19 boolean limited = false; 20 int limit = 0; 21 Lock lock = new ReentrantLock(); public int put1(int t) throws InterruptedException { 24 lock.lock(); 25 try { 26 if (limited && buf1total >= limit) return -1; 27 ++buf1total; 28 buf1.put(t); 29 return 0; 30 } finally { lock.unlock(); } 31 } 32 public int put2(int t) throws InterruptedException { 33 lock.lock(); 34 try { 35 if (limited && buf2total >= limit) return -1; 36 ++buf2total; 37 buf2.put(t); 6

7 38 return 0; 39 } finally { lock.unlock(); } 40 } 41 public int get() throws InterruptedException { 42 lock.lock(); 43 try { 44 if (limited && gettotal >= limit) return -1; 45 ++gettotal; 46 return buf1.get() + buf2.get(); 47 } finally { lock.unlock(); } 48 } 49 public void terminate() { 50 lock.lock(); 51 try { 52 if (limited) return; 53 limited = true; 54 limit = Math.max(buf1total, buf2total); 55 } finally { lock.unlock(); } 56 } 57 } An object of class Merge holds two bounded buffers, to which elements can be added using the put1() and put2() methods. The get() method returns the sum of the oldest element added by put1() and the oldest element added by put2(). If at least one of the queues is empty, get() should block until the elemets become available. Similarly, put1() and put2() should block if there is no space left in the queues. Furthermore, the Merge() class supports clean shutdown. After the terminate() method is called, the object allows adding elements only to the shorter queue (or to none if they are of equal lengths), and getting the number of elements that will allow emptying the queues, not more. If more get(), put1() or put2() calls are made, they result in -1 being returned to signal an error. There is a problem with the above code, as it does not behave correctly in some cases when different threads execute the get(), put1() and put2() methods. (8p) 3.1. Describe what erroneous behaviour you can observe by running code that uses different threads concurrently calling get(), put1() and put2() of the same Merge object. Describe the scenario that you are considering (2p), the expected observable behaviour (3p) and the actual observed behaviour (3p). (3p) 3.2. Explain the cause for the erroneous behaviour that can be observed and present a concrete execution of the program that supports your explanation. (5p) 3.3. Fix the problem that you have found by modifying the Merge class. You only need to state the changes you want to make to the code. 7

8 Part 4: Concurrent Java ii (14p) Consider a savings account shared by several people. Each person associated with the account may deposit or withdraw money from it. The current balance in the account is the sum of all deposits to date less the sum of all withdrawals to date. Clearly, the balance must never become negative. A person making a deposit never has to delay (except for mutual exclusion), but a withdrawal has to wait until there are sufficient funds. Furthermore, an account may be frozen by calling freeze(true) and unfrozen by calling freeze(false). The method returns a boolean, which indicates the frozen status before the call. A deposit from or a withdrawal to a frozen account should block until the account is unfrozen. Your task You are given the task to write a Java class that implements shared accounts. More specifically, you need to provide the following interface. The semaphore should be implemented using the following class. 1 class SharedSavingsAccount { 2 public SharedSavingsAccount(long initialbalance); 3 // Both deposit() and withdraw require a non-negative argument 4 public void deposit(int amount); 5 public void withdraw(int amount); 6 public boolean freeze(boolean freezeorunfreeze); 7 } Implement the SharedSavingsAccount class. Your solution must fulfill the following criteria: You must use Java. Your solution must support concurrent usage of the account. You are free to use any synchronization constructs. Do not care about fairness in your solution. Note Correct implementation without the freeze() method can earn up to 8 points. In the solution below, throws InterruptedException declarations have been added to the signatures of the deposit() and withdraw() methods. In an exam solution, InterruptedException may be handled in any way or ignored altogether. Import statement might be omitted from the solution as well. The presented solution uses two condition variables, but for simplicity one might be used instead. 1 import java.util.concurrent.locks.*; 2 3 class SharedSavingsAccount { 4 long balance; 5 boolean frozen = false; 6 Lock lock = new ReentrantLock(); 7 Condition morefunds = lock.newcondition(); 8 Condition unfrozen = lock.newcondition(); 8

9 9 10 public SharedSavingsAccount(long initialbalance) { 11 balance = initialbalance; 12 } public void deposit(int amount) throws InterruptedException { 15 lock.lock(); 16 try { 17 while (frozen) unfrozen.await(); 18 balance += amount; 19 morefunds.signalall(); 20 } finally { lock.unlock(); } 21 } 22 public void withdraw(int amount) throws InterruptedException { 23 lock.lock(); 24 try { 25 while (frozen balance < amount) morefunds.await(); 26 balance -= amount; 27 } finally { lock.unlock(); } 28 } 29 public boolean freeze(boolean freezeorunfreeze) { 30 lock.lock(); 31 try { 32 boolean oldfrozen = frozen; 33 frozen = freezeorunfreeze; 34 if (oldfrozen &&!freezeorunfreeze) { 35 // We need to wake up potentially everyone 36 unfrozen.signalall(); 37 morefunds.signalall(); 38 } 39 return oldfrozen; 40 } finally { lock.unlock(); } 41 } 9

10 Part 5: Concurrent Erlang (14p) In this assignment you should re-implement the shared account from Part 4 in Erlang. The solution should provide the account module that exposes the following functions to the users. 1 -module(account). 2 -export([start/1, deposit/2, withdraw/2, freeze/2]). 3 4 start(balance) ->... 5 deposit(e, Amount) ->... 6 withdraw(e, Amount) ->... 7 freeze(e, FreezeOrUnfreeze) ->... The behaviour of the deposit/2, withdraw/2 and freeze/2 functions should be the same as of the respective methods from Part 4 in particular the freeze/2 function should return a boolean. As in Part 4, the solution does not need to be fair. Efficiency is also not a concern, as long as polling or busy-waiting does not occur. Note Correct solutions without the freeze/2 function can earn up to 8 points. The following solution uses guards to delay handling of some requests. While this is not an efficient solution when many requests are delayed, it is perfectly acceptable as the task does not ask for an efficient solution. 1 -module(account). 2 -export([start/1, deposit/2, withdraw/2, freeze/2]). 3 4 start(n) -> 5 spawn(fun () -> loop(n, false) end). 6 7 loop(n, Frozen) -> 8 receive 9 {deposit, Pid, M} when not Frozen -> 10 Pid! deposit_reply, 11 loop(n + M, Frozen); 12 {withdraw, Pid, M} when not Frozen andalso M =< N -> 13 Pid! withdraw_reply, 14 loop(n - M, Frozen); 15 {freeze, Pid, FreezeOrUnfreeze} -> 16 Pid! {freeze_reply, Frozen}, 17 loop(n, FreezeOrUnfreeze) 18 end deposit(s, M) -> 21 S! {deposit, self(), M}, 22 receive deposit_reply -> ok end

11 24 withdraw(s, M) -> 25 S! {withdraw, self(), M}, 26 receive withdraw_reply -> ok end freeze(s, FreezeOrUnfreeze) -> 29 S! {freeze, self(), FreezeOrUnfreeze}, 30 receive {freeze_reply, OldFrozen} -> OldFrozen end. 11

12 Appendix Elang builtin functions Builtin functions (bifs) are functions provided by the Erlang VM. Here is a reference to several of them. register/2 register(name, Pid) registers the process Pid under the name Name, which must be an atom. If there is already a process registered under that name, the function throws an exception. When the registered process terminates, it is automatically unregistered. The registered name can be used in the send operator to send a message to a registered process (Name! Message). Sending a message using a name under which no process is registered throws an exception. Example The following example assumes that there is no processes registered as myproc and myproc2 before executing the statements, and that the first created process keeps running when all other statements are executed. 1 1> register (myproc, spawn (fun init/0)). 2 true 3 2> register (myproc, spawn (fun init/0)). 4 ** exception error: bad argument 5 in function register/2 6 called as register(myproc,<0.42.0>) 7 3> myproc!{mymessage, 3}. 8 {mymessage, 3} 9 4> myproc2!{mymessage, 3}. 10 ** exception error: bad argument 11 in operator!/2 12 called as myproc2! {mymessage, 3} whereis/1 register(name) returns the p i d of a registered process, or the atom undefined if no process is registered under this name. unregistered. Example The following example assumes that there are no processes registered as myproc and myproc2 before executing the statements and that the first created process is still running then the whereis/2 calls are executed. 1 1> register (myproc, spawn (fun init/0)). 2 true 3 2> whereis(myproc). 4 <0.48.0> 5 3> whereis(myproc2). 6 undefined 12

13 is_pid/1 is_pid(arg) returns true if its argument is a p i d, and false otherwise. Example 1 1> P = spawn (fun init/0). 2 <0.46.0> 3 2> is_pid(p). 4 true 5 3> is_pid(something_else). 6 false Java concurrency libraries Here is a reference of several concurrency-related classes. Semaphore 1 import java.util.concurrent.semaphore; 2 3 class Semaphore { 4 Semaphore(int permits); 5 Semaphore(int permits, boolean fair); 6 7 void acquire() throws InterruptedException; 8 void acquire(int permits) throws InterruptedException; 9 boolean tryacquire(); 10 boolean tryacquire(int permits); 11 void release(); 12 void release(int permits); 13 } ReentrantLock class 1 import java.util.concurrent.locks.*; 2 3 class ReentrantLock { 4 ReentrantLock(); 5 ReentrantLock(boolean fair); 6 7 void lock(); 8 boolean trylock(); 9 void unlock(); 10 Condition newcondition(); 11 } 13

14 12 13 interface Condition { 14 void await() throws InterruptedException; 15 void signal(); 16 void signalall(); 17 } Object The condition variable associated with each object to be used with synchronized is accessible using methods from the Object class. 1 class Object { 2 void wait() throws InterruptedException; 3 void notify(); 4 void notifyall(); 5 } 14

### 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

### 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

### Threads and Locks, Part 2. CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014

Threads and Locks, Part 2 CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014 1 Goals Cover the material presented in Chapter 2 of our concurrency textbook In particular, selected material

### 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

### Teaching predicates and invariants on shared data structures in concurrent programming

Teaching predicates and invariants on shared data structures in concurrent programming Stein Gjessing Department of informatics, University of Oslo steing@ifi.uio.no Arne Maus Department of informatics,

### COMP 322: Fundamentals of Parallel Programming

COMP 322: Fundamentals of Parallel Programming https://wiki.rice.edu/confluence/display/parprog/comp322 Lecture 30: Advanced locking in Java Vivek Sarkar Department of Computer Science Rice University

### CPS 310 midterm exam #1, 2/19/2016

CPS 310 midterm exam #1, 2/19/2016 Your name please: NetID: Answer all questions. Please attempt to confine your answers to the boxes provided. For the execution tracing problem (P3) you may wish to use

### 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

### CSCI 5828: Foundations of Software Engineering

CSCI 5828: Foundations of Software Engineering Lecture 16: Monitors & Condition Synchronization Slides created by Magee and Kramer for the Concurrency textbook 1 Chapter 5 Monitors & Condition Synchronization

### Lecture 10: Introduction to Semaphores

COMP 150-CCP Concurrent Programming Lecture 10: Introduction to Semaphores Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 19, 2008 Semaphores Semaphores (Dijkstra 1968) are widely

### Monitors & Condition Synchronization

Feb. 15, 2012 Monitors & condition Synchronization Concepts: monitors: encapsulated data + access procedures mutual exclusion + condition synchronization single access procedure active in the monitor Models:

### Programming Languages

Programming Languages Tevfik Koşar Lecture - XXVII May 2 nd, 2006 1 Roadmap Shared Memory Cigarette Smokers Problem Monitors Message Passing Cooperative Operations Synchronous and Asynchronous Sends Blocking

### 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

### Erlang. Functional Concurrent Distributed Soft real-time OTP (fault-tolerance, hot code update ) Open. Check the source code of generic behaviours

Lecture 10 Erlang Erlang Functional Concurrent Distributed Soft real-time OTP (fault-tolerance, hot code update ) Open Check the source code of generic behaviours 2 Functional Haskell call-by-need (lazy)

### 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

### SWEN-220 Mathematical Models of Software. Process Synchronization Critical Section & Semaphores

SWEN-220 Mathematical Models of Software Process Synchronization Critical Section & Semaphores 1 Topics The critical section Synchronization using busy-wait Semaphores 2 The Critical Section Processes

### Midterm #1. CMSC 433: Programming Language Technologies and Paradigms. October 14, 2013

Midterm #1 CMSC 433: Programming Language Technologies and Paradigms October 14, 2013 Name Instructions Do not start until told to do so! This exam has 10 double-sided pages (including this one); make

### CSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014

CSE 332: Locks and Deadlocks Richard Anderson, Steve Seitz Winter 2014 1 Recall Bank Account Problem class BankAccount { private int balance = 0; synchronized int getbalance() { return balance; } synchronized

### 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

### Midterm on next week Tuesday May 4. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9

CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

### 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

### G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency Lecture 11: Semaphores I" Brian Logan School of Computer Science bsl@cs.nott.ac.uk Outline of this lecture" problems with Peterson s algorithm semaphores implementing semaphores

### CPS 110 Midterm. Spring 2011

CPS 110 Midterm Spring 2011 Ola! Greetings from Puerto Rico, where the air is warm and salty and the mojitos are cold and sweet. Please answer all questions for a total of 200 points. Keep it clear and

### Synchronization: Semaphores

Illinois Institute of Technology Lecture 26 4/25 solved Synchronization: Semaphores CS 536: Science of Programming, Spring 2018 A. Why Avoiding interference, while good, isn t the same as coordinating

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

Semaphore Semaphore S integer variable Two standard operations modify S: wait() and signal() Originally called P() and V() Can only be accessed via two indivisible (atomic) operations wait (S) { while

### Midterm Exam Amy Murphy 19 March 2003

University of Rochester Midterm Exam Amy Murphy 19 March 2003 Computer Systems (CSC2/456) Read before beginning: Please write clearly. Illegible answers cannot be graded. Be sure to identify all of your

### Monitors & Condition Synchronization

Chapter 5 Monitors & Condition Synchronization monitors & condition synchronization Concepts: monitors: encapsulated data + access procedures mutual exclusion + condition synchronization single access

### Concurrent Programming Benoît Garbinato

Concurrent Programming Benoît Garbinato 1 Processes & threads A process is a unit of execution managed at the level of the operating system Each process has its own address space, i.e., no other process

### Processor speed. Concurrency Structure and Interpretation of Computer Programs. Multiple processors. Processor speed. Mike Phillips <mpp>

Processor speed 6.037 - Structure and Interpretation of Computer Programs Mike Phillips Massachusetts Institute of Technology http://en.wikipedia.org/wiki/file:transistor_count_and_moore%27s_law_-

### Do not start the test until instructed to do so!

CS 3204 Operating Systems Midterm (Abrams) Spring 2004 VIRG INIA POLYTECHNIC INSTITUTE AND STATE U T PRO SI M UNI VERSI TY Instructions: Do not start the test until instructed to do so! Print your name

### 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

### 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)

### Programming Language Concepts: Lecture 11

Programming Language Concepts: Lecture 11 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2011, Lecture 11, 01 March 2011 Concurrent Programming Monitors [Per Brinch Hansen, CAR Hoare]

### Last Class: CPU Scheduling! Adjusting Priorities in MLFQ!

Last Class: CPU Scheduling! Scheduling Algorithms: FCFS Round Robin SJF Multilevel Feedback Queues Lottery Scheduling Review questions: How does each work? Advantages? Disadvantages? Lecture 7, page 1

### 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

### Monitors & Condition Synchronization

Chapter 5 Monitors & Condition Synchronization controller 1 Monitors & Condition Synchronization Concepts: monitors (and controllers): encapsulated data + access procedures + mutual exclusion + condition

### Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

CMSC 330: Organization of Programming Languages Threads Computation Abstractions t1 t2 t1 t3 t2 t1 p1 p2 p3 p4 CPU 1 CPU 2 A computer t4 t5 Processes (e.g., JVM s) Threads CMSC 330 2 Processes vs. Threads

### UNIX Input/Output Buffering

UNIX Input/Output Buffering When a C/C++ program begins execution, the operating system environment is responsible for opening three files and providing file pointers to them: stdout standard output stderr

### First Midterm Exam September 28, 2017 CS162 Operating Systems

University of California, Berkeley College of Engineering Computer Science Division EECS Fall 2017 Ion Stoica First Midterm Exam September 28, 2017 CS162 Operating Systems Your Name: SID AND 162 Login

### Reminder from last time

Concurrent systems Lecture 5: Concurrency without shared data, composite operations and transactions, and serialisability DrRobert N. M. Watson 1 Reminder from last time Liveness properties Deadlock (requirements;

### A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 4 Shared-Memory Concurrency & Mutual Exclusion

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 4 Shared-Memory Concurrency & Mutual Exclusion Dan Grossman Last Updated: August 2010 For more information, see http://www.cs.washington.edu/homes/djg/teachingmaterials/

### Message-passing concurrency in Erlang

Message-passing concurrency in Erlang Lecture 8 of TDA383/DIT390 (Concurrent Programming) Carlo A. Furia Chalmers University of Technology University of Gothenburg SP3 2016/2017 Today s menu Actors and

### CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

CMSC 433 Programming Language Technologies and Paradigms Composing Objects Composing Objects To build systems we often need to Create thread safe objects Compose them in ways that meet requirements while

### CS193k, Stanford Handout #8. Threads 3

CS193k, Stanford Handout #8 Spring, 2000-01 Nick Parlante Threads 3 t.join() Wait for finish We block until the receiver thread exits its run(). Use this to wait for another thread to finish. The current

### Concurrent Queues, Monitors, and the ABA problem. Companion slides for The Art of Multiprocessor Programming by Maurice Herlihy & Nir Shavit

Concurrent Queues, Monitors, and the ABA problem Companion slides for The Art of Multiprocessor Programming by Maurice Herlihy & Nir Shavit Queues Often used as buffers between producers and consumers

### 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

### 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 /

### Roadmap. Tevfik Ko!ar. CSC Operating Systems Fall Lecture - XI Deadlocks - II. Louisiana State University

CSC 4103 - Operating Systems Fall 2009 Lecture - XI Deadlocks - II Tevfik Ko!ar Louisiana State University September 29 th, 2009 1 Roadmap Classic Problems of Synchronization Bounded Buffer Readers-Writers

### COMP346 Winter Tutorial 4 Synchronization Semaphores

COMP346 Winter 2015 Tutorial 4 Synchronization Semaphores 1 Topics Synchronization in Details Semaphores Introducing Semaphore.java 2 Synchronization What is it? An act of communication between unrelated

### 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,

### Summer Final Exam Review Session August 5, 2009

15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

### Lecture 6. Introduction to Message Passing

Lecture 6 Introduction to Message Passing Message Passing Introduction to message passing JR s message passing model Operations Asynchronous message passing Synchronous message passing 2 Shared Variables?

### Synchronization via Transactions

Synchronization via Transactions 1 Concurrency Quiz If two threads execute this program concurrently, how many different final values of X are there? Initially, X == 0. Thread 1 Thread 2 void increment()

### Synchronization I. Jo, Heeseung

Synchronization I Jo, Heeseung Today's Topics Synchronization problem Locks 2 Synchronization Threads cooperate in multithreaded programs To share resources, access shared data structures Also, to coordinate

### CS162 Operating Systems and Systems Programming Lecture 8. Readers-Writers Language Support for Synchronization

Review: Implementation of Locks by Disabling Interrupts CS162 Operating Systems and Systems Programming Lecture 8 Readers-Writers Language Support for Synchronization September 27, 2010 Prof John Kubiatowicz

### RACE CONDITIONS AND SYNCHRONIZATION

RACE CONDITIONS AND SYNCHRONIZATION Lecture 21 CS2110 Fall 2010 Reminder 2 A race condition arises if two threads try and share some data One updates it and the other reads it, or both update the data

### Using the Xcode Debugger

g Using the Xcode Debugger J Objectives In this appendix you ll: Set breakpoints and run a program in the debugger. Use the Continue program execution command to continue execution. Use the Auto window

### Condition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois

Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois 1 Synchronization primitives Mutex locks Used for exclusive access to a shared resource (critical section) Operations:

### CSE 120. Fall Lecture 6: Semaphores. Keith Marzullo

CSE 120 Principles of Operating Systems Fall 2007 Lecture 6: Semaphores Keith Marzullo Announcements Homework #2 out Homework #1 almost graded... Discussion session on Wednesday will entertain questions

### Comp 204: Computer Systems and Their Implementation. Lecture 25a: Revision Lectures (separate questions and answers)

Comp 204: Computer Systems and Their Implementation Lecture 25a: Revision Lectures (separate questions and answers) 1 Today Here are a sample of questions that could appear in the exam Please LET ME KNOW

### 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

### Midterm Exam Solutions and Grading Guidelines March 3, 1999 CS162 Operating Systems

University of California, Berkeley College of Engineering Computer Science Division EECS Spring 1999 Anthony D. Joseph Midterm Exam Solutions and Grading Guidelines March 3, 1999 CS162 Operating Systems

### THE QUEEN S UNIVERSITY OF BELFAST

THE QUEEN S UNIVERSITY OF BELFAST FSP Quick Reference Guide is attached to the end of the examination paper. 110CSC321 Level 3 EXAMINATION FOR THE DEGREE(S) OF MEng, BEng, BSc Concurrent Programming January

### Race Conditions & Synchronization

Race Conditions & Synchronization Lecture 25 Spring 2017 Gries office hours 2 A number of students have asked for time to talk over how to study for the prelim. Gries will hold office hours at the times

### COP 5611 Operating Systems Spring Dan C. Marinescu Office: HEC 439 B Office hours: M-Wd 2:00-3:00 PM

COP 5611 Operating Systems Spring 2010 Dan C. Marinescu Office: HEC 439 B Office hours: M-Wd 2:00-3:00 PM Lecture 7 Last time: Thread coordination Today: Thread coordination Scheduling Multi-level memories

### Single processor CPU. Memory I/O

Lec 17 Threads Single processor CPU Memory I/O Multi processes Eclipse PPT iclicker Multi processor CPU CPU Memory I/O Multi-core Core Core Core Core Processor Memory I/O Logical Cores Multi-threaded

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

### 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

### + Today. Lecture 26: Concurrency 3/31/14. n Reading. n Objectives. n Announcements. n P&C Section 7. n Race conditions.

+ Lecture 26: Concurrency Slides adapted from Dan Grossman + Today n Reading n P&C Section 7 n Objectives n Race conditions n Announcements n Quiz on Friday 1 + This week s programming assignment n Answer

### Semaphores INF4140. Lecture 3. 0 Book: Andrews - ch.04 ( ) INF4140 ( ) Semaphores Lecture 3 1 / 34

Semaphores INF4140 13.09.12 Lecture 3 0 Book: Andrews - ch.04 (4.1-4.4) INF4140 (13.09.12 ) Semaphores Lecture 3 1 / 34 Overview Last lecture: Locks and Barriers (complex techniques) No clear difference

### 7. Testing and Debugging Concurrent Programs

7. Testing and Debugging Concurrent Programs The purpose of testing is to find program failures => A successful test is a test that causes a program to fail. Ideally, tests are designed before the program

### 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 thread safety and Concurrent collections. Nasser Giacaman CompSci 230: Software Design and Construction

More thread safety and Concurrent collections Nasser Giacaman CompSci 230: Software Design and Construction 1 Today's lecture More on Java's mutual exclusion tools Intrinsic locks Developing our own thread-safe

### Component-Based Software Engineering

Component-Based Software Engineering More stuff on Threads Paul Krause Lecture 7 - Contents Basics of threads and synchronization Waiting - releasing locks Collection Plate example Choices when pausing

### Tool demonstration: Spin

Tool demonstration: Spin 1 Spin Spin is a model checker which implements the LTL model-checking procedure described previously (and much more besides). Developed by Gerard Holzmann of Bell Labs Has won

### Process Synchronization

Process Synchronization Concurrent access to shared data in the data section of a multi-thread process, in the shared memory of multiple processes, or in a shared file Although every example in this chapter

### Synchronization. CSCI 5103 Operating Systems. Semaphore Usage. Bounded-Buffer Problem With Semaphores. Monitors Other Approaches

Synchronization CSCI 5103 Operating Systems Monitors Other Approaches Instructor: Abhishek Chandra 2 3 Semaphore Usage wait(s) Critical section signal(s) Each process must call wait and signal in correct

### DUBLIN CITY UNIVERSITY

DUBLIN CITY UNIVERSITY SEMESTER ONE RESIT EXAMINATIONS 2012 MODULE TITLE: MODULE CODE: COURSE: Concurrent Programming CA463/CA463D BSc. in Computer Applications (Software Engineering Stream), Study Abroad

### CS420: Operating Systems. Process Synchronization

Process Synchronization James Moscola Department of Engineering & Computer Science York College of Pennsylvania Based on Operating System Concepts, 9th Edition by Silberschatz, Galvin, Gagne Background

### CSCI 201L Final Written Spring % of course grade

Name SOLUTION Final Score ID Extra Credit Section (circle one): MW 8:30-9:50 TTh 9:30-10:50 TTh 11:00-12:20 12% of course grade 1. Servlets Explain the difference between a GET and POST form submission.

### Resource Sharing & Management

Resource Sharing & Management P.C.P Bhatt P.C.P Bhatt OS/M6/V1/2004 1 Introduction Some of the resources connected to a computer system (image processing resource) may be expensive. These resources may

### CS 160: Interactive Programming

CS 160: Interactive Programming Professor John Canny 3/8/2006 1 Outline Callbacks and Delegates Multi-threaded programming Model-view controller 3/8/2006 2 Callbacks Your code Myclass data method1 method2

### 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

### Outline of lecture. i219 Software Design Methodology 10. Multithreaded programming. Kazuhiro Ogata (JAIST)

i219 Software Design Methodology 10. Multithreaded programming Kazuhiro Ogata (JAIST) Outline of lecture 2 Thread Race condition Synchronization Deadlock Bounded buffer problem Thread (1) 3 Units of execution.

### Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

CMSC 330: Organization of Programming Languages OCaml 1 Functional Programming Dialects of ML ML (Meta Language) Univ. of Edinburgh,1973 Part of a theorem proving system LCF The Logic of Computable Functions

### Stanford University Computer Science Department CS 140 Midterm Exam Dawson Engler Winter 1999

Stanford University Computer Science Department CS 140 Midterm Exam Dawson Engler Winter 1999 Name: Please initial the bottom left corner of each page. This is an open-book exam. You have 50 minutes to

### Synchronization II: EventBarrier, Monitor, and a Semaphore. COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala

Synchronization II: EventBarrier, Monitor, and a Semaphore COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala Check point: Mission in progress Master synchronization techniques Develop best practices for

### CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 Lecture #13, Concurrency, Interference, and Synchronization John Ridgway March 12, 2015 Concurrency and Threads Computers are capable of doing more

### Lab 7: OCaml 12:00 PM, Oct 22, 2017

CS17 Integrated Introduction to Computer Science Hughes Lab 7: OCaml 12:00 PM, Oct 22, 2017 Contents 1 Getting Started in OCaml 1 2 Pervasives Library 2 3 OCaml Basics 3 3.1 OCaml Types........................................

### Answer Key. 1. General Understanding (10 points) think before you decide.

Answer Key 1. General Understanding (10 points) Answer the following questions with yes or no. think before you decide. Read the questions carefully and (a) (2 points) Does the interface java.util.sortedset

### BlockingArrayQueue.java. Page 1

1 //BlockingArrayQueue.java 2 //Template blocking queue class, implemented with emulated circular array. 3 //Programmer: Randy Miller 4 //Last modification: April 13, 2015 5 6 7 8 import java.util.arraylist;

### Concurrency Race Conditions and Deadlocks

Concurrency Race Conditions and Deadlocks Kartik Gopalan Chapters 2 (2.3) and 6 Tanenbaum s Modern OS Sequential Loosely, doing many things, but one after another E.g. Finish one assignment, then another

### 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.,

### Final Exam. Kenneth J. Goldman December 18, Name: Student ID Number: Signature:

Washington University CSE131. Computer Science I Final Exam Kenneth J. Goldman December 18, 2007 Name: Student ID Number: Signature: Directions: This exam is closed book and closed notes. No electronic

### 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