Futures. COS 326 David Walker Princeton University
|
|
- Charlene Nash
- 5 years ago
- Views:
Transcription
1 Futures COS 326 David Walker Princeton University
2 Futures module type FUTURE = sig type a future (* future f x forks a thread to run f(x) and stores the result in a future when complete *) val future : ( a-> b) -> a -> b future (* force f causes us to wait until the thread computing the future value is done and then returns its value. *) val force : a future -> a end 2
3 Future Implementa?on (Version 1) module Future : FUTURE = struct type a future = {tid : Thread.t ; value : a option ref } end 3
4 Future Implementa?on (Version 1) module Future : FUTURE = struct type a future = {tid : Thread.t ; value : a option ref } let future(f: a-> b)(x: a) : b future = let r = ref None in let t = Thread.create (fun () -> r := Some(f x)) () in {tid=t ; value=r} end 4
5 Future Implementa?on (Version 1) module Future : FUTURE = struct type a future = {tid : Thread.t ; value : a option ref } let future(f: a-> b)(x: a) : b future = let r = ref None in let t = Thread.create (fun () -> r := Some(f x)) () in {tid=t ; value=r} end let force (f: a future) : a = Thread.join f.tid ; match!(f.value) with Some v -> v None -> failwith impossible! 5
6 Now using Futures let x = future f () in let y = g () in let v = force x in (* compute with v and y *) 6
7 Compiling Create a _tags file in your directory: _tags: true: thread, package(threads) Invoke ocamlbuild from your shell (code in future.ml): $ ocamlbuild -use-ocamlfind future.d.byte
8 Back to the Futures module type FUTURE = sig type a future val future : ( a-> b) -> a -> b future val force : a future -> a end val f : unit -> int val g : unit -> int with futures library: let x = future f () in let y = g () in let v = force x in y + v without futures library: let r = ref None let t = Thread.create (fun _ -> r := Some(f ())) () in let y = g() in Thread.join t ; match!r with Some v -> y + v None -> failwith impossible 8
9 Back to the Futures module type FUTURE = sig type a future val future : ( a-> b) -> a -> b future val force : a future -> a end val f : unit -> int val g : unit -> int with futures library: let x = future f () in let y = g () in let v = force x in y + v what happens if we delete these lines? without futures library: let r = ref None let t = Thread.create (fun _ -> r := Some(f ())) () in let y = g() in Thread.join t ; match!r with Some v -> y + v None -> failwith impossible 9
10 Back to the Futures module type FUTURE = sig type a future val future : ( a-> b) -> a -> b future val force : a future -> a end val f : unit -> int val g : unit -> int with futures library: let x = future f () in let y = g () in let v = force x in y + x what happens if we use x and forget to force? without futures library: let r = ref None let t = Thread.create (fun _ -> r := Some(f ())) () in let y = g() in Thread.join t ; match!r with Some v -> y + v None -> failwith impossible 10
11 Back to the Futures module type FUTURE = sig type a future val future : ( a-> b) -> a -> b future val force : a future -> a end val f : unit -> int val g : unit -> int with futures library: let x = future f () in let y = g () in let v = force x in y + x Moral: Futures + typing ensure en?re categories of errors can t happen - - you protect yourself from your own stupidity without futures library: let r = ref None let t = Thread.create (fun _ -> r := Some(f ())) () in let y = g() in Thread.join t ; match!r with Some v -> y + v None -> failwith impossible 11
12 Back to the Futures module type FUTURE = sig type a future val future : ( a-> b) -> a -> b future val force : a future -> a end val f : unit -> int val g : unit -> int with futures library: let x = future f () in let v = force x in let y = g () in y + x what happens if you relocate force, join? without futures library: let r = ref None let t = Thread.create (fun _ -> r := Some(f ())) () in Thread.join t ; let y = g() in match!r with Some v -> y + v None -> failwith impossible 12
13 Back to the Futures module type FUTURE = sig type a future val future : ( a-> b) -> a -> b future val force : a future -> a end val f : unit -> int val g : unit -> int with futures library: let x = future f () in let v = force x in let y = g () in y + x Moral: Futures are not a universal savior without futures library: let r = ref None let t = Thread.create (fun _ -> r := Some(f ())) () in Thread.join t ; let y = g() in match!r with Some v -> y + v None -> failwith impossible 13
14 An Example: Mergesort on Arrays let mergesort (cmp:'a->'a->int) (arr : 'a array) : 'a array = let rec msort (start:int) (len:int) : 'a array = match len with 0 -> Array.of_list [] 1 -> Array.make 1 arr.(start) _ -> let half = len / 2 in let a1 = msort start half in let a2 = msort (start + half) merge a1 a2 (len - half) in and merge (a1:'a array) (a2:'a array) : 'a array =... 14
15 An Example: Mergesort on Arrays let mergesort (cmp:'a->'a->int) (arr : 'a array) : 'a array = let rec msort (start:int) (len:int) : 'a array = match len with 0 -> Array.of_list [] 1 -> Array.make 1 arr.(start) _ -> let half = len / 2 in let a1 = msort start half in let a2 = msort (start + half) (len - half) in merge a1 a2 and merge (a1:'a array) (a2:'a array) : 'a array = let a = Array.make (Array.length a1 + Array.length a2) a1.(0) in let rec loop i j k = match i < Array.length a1, j < Array.length a2 with true, true -> if cmp a1.(i) a2.(j) <= 0 then (a.(k) <- a1.(i) ; loop (i+1) j (k+1)) else (a.(k) <- a2.(j) ; loop i (j+1) (k+1)) true, false -> a.(k) <- a1.(i) ; loop (i+1) j (k+1) false, true -> a.(k) <- a2.(j) ; loop i (j+1) (k+1) false, false -> () in loop ; a in msort 0 (Array.length arr) 15
16 An Example: Mergesort on Arrays let mergesort (cmp:'a->'a->int) (arr : 'a array) : 'a array = let rec msort (start:int) (len:int) : 'a array Opportunity = for paralleliza?on match len with 0 -> Array.of_list [] 1 -> Array.make 1 arr.(start) _ -> let half = len / 2 in let a1 = msort start half in let a2 = msort (start + half) merge a1 a2 (len - half) in and merge (a1:'a array) (a2:'a array) : 'a array =... 16
17 Making Mergesort Parallel let mergesort (cmp:'a->'a->int) (arr : 'a array) : 'a array = let rec msort (start:int) (len:int) : 'a array = match len with 0 -> Array.of_list [] 1 -> Array.make 1 arr.(start) _ -> let half = len / 2 in let a1_f = Future.future (msort start) half in let a2 = msort (start + half) (len - half) in merge (Future.force a1_f) a2 and merge (a1:'a array) (a2:'a array) : 'a array =... 17
18 Making it Pre_er We've seen this a lot: let a1 = Future.future f x in let a2 = g y in... (Future.force a1)... a
19 Making it Pre_er We've seen this a lot: let a1 = Future.future f x in let a2 = g y in... (Future.force a1).. a2 Let's build another abstrac?on that evaluates a pair of func?ons in parallel: let both f x g y = let a1 = Future.future f x in let a2 = g y in (Future.force a1, a2) 19
20 Making it Pre_er We've seen this a lot: let a1 = Future.future f x in let a2 = g y in... (Future.force a1)... a2... let a1, a2 = both f x g y in... a1... a
21 Making Mergesort Parallel let mergesort (cmp:'a->'a->int) (arr : 'a array) : 'a array = let rec msort (start:int) (len:int) : 'a array = match len with 0 -> Array.of_list [] 1 -> Array.make 1 arr.(start) _ -> let half = len / 2 in let a1,a2 = both (msort start) half in merge a1 a2 (msort (start + half)) (len half) and merge (a1:'a array) (a2:'a array) : 'a array = 21
22 Divide- and- Conquer This is an instance of a basic divide- and- conquer padern in parallel programming take the problem to be solved and divide it in half fork a thread to solve the first half simultaneously solve the second half synchronize with the thread we forked to get its results combine the two solu?on halves into a solu?on for the whole problem. Warning: the fact that we only had to rewrite 2 lines of code for mergesort made the paralleliza?on transforma?on look decep?vely easy we also had to verify that any two threads did not touch overlapping por?ons of the array - - if they did we would have to again worry about scheduling non- determinism 22
23 Caveats There is some overhead for crea?ng a thread. On a uni- processor, parallel code will run slower than the sequen?al code. Even on a mul?- processor, we probably do not always want to fork a thread when the sub- array is small, faster to sort it than to fork a thread to sort it. similar to using inser?on sort when arrays are small vs. quicksort this is known as a granularity problem more parallelism than we can effec?vely take advantage of. 23
24 Caveats In a good implementa?on of futures, a compiler and run-?me system might look to see whether the cost of doing the fork is jus?fied by the amount of work that will be done. Today, it s up to you to figure this out L typically, use parallel divide- and- conquer un?l (a) we have generated at least as many threads as there are processors ogen more threads than processors because different jobs take different amounts of?me to complete and we would like to keep all processors busy (b) the sub- arrays have goden small enough that it s not worth forking. 24
25 Another Example type 'a tree = Leaf Node of 'a node and 'a node = {left : 'a tree ; value : 'a ; right : 'a tree } let rec fold (f:'a -> 'b -> 'b -> 'b) (u:'b) (t:'a tree) : 'b = match t with Leaf -> u Node n -> let l,r = (fold f u n.left, in f n.value l r fold f u n.right) let sum (t:int tree) = fold (+) 0 t 25
26 Another Example type 'a tree = Leaf Node of 'a node and 'a node = {left : 'a tree ; value : 'a ; right : 'a tree } let rec pfold (f:'a -> 'b -> 'b -> 'b) (u:'b) (t:'a tree) : 'b = match t with Leaf -> u Node n -> let l,r = both (pfold f u) n.left (pfold f u) n.right in f n.value l r let sum (t:int tree) = pfold (+) 0 t 26
27 Note If the tree is imbalanced, then we re not going to get the same speedup as if it s balanced. Consider the degenerate case of a list. The forked child will terminate without doing any useful work. So the parent is going to have to do all that work. Pure overhead L In general, lists are a horrible data structure for parallelism. we can t cut the list in half in constant :me for arrays and trees, we can do that (assuming the tree is balanced.) 27
28 REVISITING OUR FUTURE IMPLEMENTATION
29 Excep?ons and Futures exception Hello let main () = let x = Future.future (fun x -> raise Hello) () in try force x with Hello -> print_endline "world" let _ = main () What happens now?
30 Excep?ons and Futures exception Hello let main () = let x = Future.future (fun x -> raise Hello) () in try force x with Hello -> print_endline "world" let _ = main () $./future.d.byte Thread 1 killed on uncaught exception Future.Hello Fatal error: exception Failure("impossible!")
31 Future Implementa?on (Version 2) module Future : FUTURE = struct type 'a result = Unevaluated Evaluated of 'a Exception of exn type 'a future = { tid: Thread.t; result: 'a result ref } let future f x = let r = ref Unevaluated in... let work () = try r := Evaluated (f x) with e -> r := Exception e in let t = Thread.create work () in {tid=t ; result=r} 31
32 Future Implementa?on (Version 2) module Future : FUTURE = struct type 'a result = Unevaluated Evaluated of 'a Exception of exn type 'a future = { tid: Thread.t; result: 'a result ref }... end let force (f:'a future) : 'a = Thread.join f.tid; match!(f.result) with Evaluated v -> v Exception e -> raise e Unevaluated -> failwith "impossible!" 32
33 Future Implementa?on (Version 2) module Future : FUTURE exception Hello let main () = let x = future (fun x -> raise Hello) () in try force x with Hello -> print_endline "world" let _ = main () 33
34 Future Implementa?on (Version 2) module Future : FUTURE exception Hello let main () = let x = future (fun x -> raise Hello) () in try force x with Hello -> print_endline "world" let _ = main () $./future.d.byte world 34
35 Other Side Effects? type 'a tree = Leaf Node of 'a node and 'a node = { left : 'a tree ; value : 'a ; right : 'a tree } let rec pfold (f:'a -> 'b -> 'b -> 'b) (u:'b) (t:'a tree) : 'b = match t with Leaf -> u Node n -> let l,r = both (pfold f u) n.left (pfold f u) n.right in f n.value l r let print (t:int tree) = pfold (fun n -> Printf.print %d\n n) () 35
36 Pure Func?ons A func?on (or expression) is pure if it has no effects. (Valuable expressions are pure) Recall that a func?on has an effect if its behavior cannot be completely explained by a determinis:c, total func?on that relates its inputs and its outputs Expressions have effects when they: don't terminate raise excep?ons read from stdin/print to stdout read or write to a shared mutable data structure increasingly difficult to deal with Not an effect: reading from immutable data structures
37 Benign Effects & Futures What if your program has effects? (Most useful programs do!) Try to push the effects to the edges of your program and put parallelism in the middle. Especially limit mutable data. let main () = effect let main () = effect effect effect effect pure parallelism
38 REASONING PRINCIPLES
39 Huge Point If code is purely func:onal, then it never maaers in what order it is run. If f () and g () are pure then the following are equivalent: if f, g are total func?ons (f (), g ()) == both f () g () 39
40 Huge Point If code is purely func:onal, then it never maaers in what order it is run. If f () and g () are pure then the following are equivalent: if f, g are total func?ons (f (), g ()) == both f () g () let x = e1 in e2 == let x = future (fun _ -> e1) () in e2[force x/x] if e1 is valuable 40
41 Huge Point If code is purely func:onal, then it never maaers in what order it is run. If f () and g () are pure then the following are equivalent: if f, g are total func?ons (f (), g ()) == both f () g () let x = e1 in e2 == let x = future (fun _ -> e1) () in e2[force x/x] if e1 is valuable If your code contains no other effects, futures do not introduce non- determinism! Consequence: when it comes to reasoning about the correctness of your programs, we can reduce the problem of reasoning about pure func?onal code + parallel futures to the problem of reasoning about pure func?onal sequen?al code! 41
42 if e1 is valuable then: let x = e1 in e2 Example Transforma?on == let x = future (fun _ -> e1) () in e2[force x/x] type 'a tree = Leaf Node of 'a * 'a tree * 'a tree let rec fold (f:'a -> 'b -> 'b -> 'b) (u:'b) (t:'a tree) : 'b = match t with Leaf -> u Node (n,left,right) -> let left' = fold f u left in let right' = fold f u right in f n left' right'
43 if e1 is valuable then: let x = e1 in e2 Example Transforma?on == let x = future (fun _ -> e1) () in e2[force x/x] type 'a tree = Leaf Node of 'a * 'a tree * 'a tree let rec fold (f:'a -> 'b -> 'b -> 'b) (u:'b) (t:'a tree) : 'b = match t with Leaf -> u Node (n,left,right) -> let left' = future (fun _ -> fold f u left) () in let right' = fold f u right in f n (force left') right'
44 if e1 is valuable then: let x = e1 in e2 Example Transforma?on == let x = future (fun _ -> e1) () in e2[force x/x] type 'a tree = Leaf Node of 'a * 'a tree * 'a tree let rec fold (f:'a -> 'b -> 'b -> 'b) (u:'b) (t:'a tree) : 'b = match t with Leaf -> u Node (n,left,right) -> let left' = future (fun _ -> fold f u left) () in let right' = fold f u right in f n (force left') right' Moral: It is vastly easier to introduce parallelism in to a pure func:onal program using futures than in to an impera?ve program with effects
45 END
Parallelism and Concurrency. COS 326 David Walker Princeton University
Parallelism and Concurrency COS 326 David Walker Princeton University Data Centers: Generation Z Super Computers Power to chip peaking Darn! Intel engineers no longer optimize my programs while I watch
More informationParallelism. COS 326 David Walker Princeton University
Parallelism COS 326 David Walker Princeton University slides copyright 2013-2015 David Walker permission granted to reuse these slides for non-commercial educa?onal purposes Parallelism What is it? Why
More informationThinking Induc,vely. COS 326 David Walker Princeton University
Thinking Induc,vely COS 326 David Walker Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel permission granted to reuse these slides for non-commercial educa,onal purposes
More informationCOS 326 David Walker Princeton University
F# COS 326 David Walker Princeton University Slide credits: Material drawn from: hbps://fsharpforfunandprofit.com/posts/computahon-expressions-intro/ hbps://fsharpforfunandprofit.com/posts/concurrency-async-and-parallel/
More informationMutation. COS 326 David Walker Princeton University
Mutation COS 326 David Walker Princeton University Mutation? 2 Thus far We have considered the (almost) purely functional subset of Ocaml. We ve had a few side effects: printing & raising exceptions. Two
More informationParallelism; Parallel Collections
Parallelism; Parallel Collections COS 326 Andrew W. Appel Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel let x = 1 + 2 in 3 + x Visualizing Computational Costs Visualizing
More informationParallel Operations on Collections. Parallel Programming in Scala Viktor Kuncak
Parallel Operations on Collections Parallel Programming in Scala Viktor Kuncak Parallelism and collections Parallel processing of collections is important one the main applications of parallelism today
More informationMuta%on. COS 326 David Walker Princeton University
Muta%on COS 326 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa%onal purposes Reasoning about Mutable State is Hard
More informationThreads and Continuations COS 320, David Walker
Threads and Continuations COS 320, David Walker Concurrency Concurrency primitives are an important part of modern programming languages. Concurrency primitives allow programmers to avoid having to specify
More informationA Func'onal Introduc'on. COS 326 David Walker Princeton University
A Func'onal Introduc'on COS 326 David Walker Princeton University Thinking Func'onally In Java or C, you get (most) work done by changing something temp = pair.x; pair.x = pair.y; pair.y = temp; commands
More informationThinking Induc,vely. COS 326 David Walker Princeton University
Thinking Induc,vely COS 326 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa,onal purposes Administra,on 2 Assignment
More informationCSE 332: Data Structures & Parallelism Lecture 12: Comparison Sorting. Ruth Anderson Winter 2019
CSE 332: Data Structures & Parallelism Lecture 12: Comparison Sorting Ruth Anderson Winter 2019 Today Sorting Comparison sorting 2/08/2019 2 Introduction to sorting Stacks, queues, priority queues, and
More informationCS 11 Ocaml track: lecture 3
CS 11 Ocaml track: lecture 3 n Today: n A (large) variety of odds and ends n Imperative programming in Ocaml Equality/inequality operators n Two inequality operators: and!= n Two equality operators:
More informationParallelism and Concurrency (Part II) COS 326 David Walker Princeton University
Parallelism and Concurrency (Part II) COS 326 David Walker Princeton University let x = 1 + 2 in 3 + x Visualizing ComputaConal Costs Visualizing ComputaConal Costs x = 1 + 2 let x = 1 + 2 in 3 + x 3 +
More informationBalanced Trees. Nate Foster Spring 2018
Balanced Trees Nate Foster Spring 2018 Prelim I Tonight! 5:30 7:30 Bring your Cornell ID Card If you have a letter allowing you special accommodations for the exam, send mail to cs3110-profs-l@list.cornell.edu
More informationCS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017
CS 137 Part 8 Merge Sort, Quick Sort, Binary Search November 20th, 2017 This Week We re going to see two more complicated sorting algorithms that will be our first introduction to O(n log n) sorting algorithms.
More informationCOS 226 Midterm Exam, Spring 2009
NAME: login ID: precept: COS 226 Midterm Exam, Spring 2009 This test is 10 questions, weighted as indicated. The exam is closed book, except that you are allowed to use a one page cheatsheet. No calculators
More informationF# Overview: Immutable Data + Pure Func7ons
F# Overview: Immutable Data + Pure Func7ons Acknowledgements Authored by Thomas Ball, MSR Redmond Includes content from the F# team Func7onal Languages Focus on data Immutability Applica7ve data transforma7ons
More informationBalanced Trees. Prof. Clarkson Fall Today s music: Get the Balance Right by Depeche Mode
Balanced Trees Prof. Clarkson Fall 2017 Today s music: Get the Balance Right by Depeche Mode Prelim See Piazza post @422 Makeup: Thursday night 5:30 pm Wed noon: All requests for other makeup/conflict
More informationA Func'onal Space Model
A Func'onal Space Model COS 26 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa'onal purposes 2 Because Halloween draws
More informationOption Values, Arrays, Sequences, and Lazy Evaluation
Option Values, Arrays, Sequences, and Lazy Evaluation Björn Lisper School of Innovation, Design, and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ Option Values, Arrays,
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 8 February 1, 2016 BST Delete Generics (Chapters 7 & 8) Announcements Read Chapters 7 & 8 (BSTs, generics) of lecture notes Read Chapter 9 of lecture
More informationDATA STRUCTURES AND ALGORITHMS
DATA STRUCTURES AND ALGORITHMS Fast sorting algorithms Shellsort, Mergesort, Quicksort Summary of the previous lecture Why sorting is needed? Examples from everyday life What are the basic operations in
More informationA Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 3 Parallel Prefix, Pack, and Sorting
A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 3 Parallel Prefix, Pack, and Sorting Dan Grossman Last Updated: November 2012 For more information, see http://www.cs.washington.edu/homes/djg/teachingmaterials/
More informationCSE 373: Data Structures & Algorithms More Sor9ng and Beyond Comparison Sor9ng
CSE 373: Data Structures & More Sor9ng and Beyond Comparison Sor9ng Riley Porter Winter 2017 1 Course Logis9cs HW5 due in a couple days à more graphs! Don t forget about the write- up! HW6 out later today
More informationTable ADT and Sorting. Algorithm topics continuing (or reviewing?) CS 24 curriculum
Table ADT and Sorting Algorithm topics continuing (or reviewing?) CS 24 curriculum A table ADT (a.k.a. Dictionary, Map) Table public interface: // Put information in the table, and a unique key to identify
More informationAtomicity via Source-to-Source Translation
Atomicity via Source-to-Source Translation Benjamin Hindman Dan Grossman University of Washington 22 October 2006 Atomic An easier-to-use and harder-to-implement primitive void deposit(int x){ synchronized(this){
More information(Func&onal (Programming (in (Scheme)))) Jianguo Lu
(Func&onal (Programming (in (Scheme)))) Jianguo Lu 1 Programming paradigms Func&onal No assignment statement No side effect Use recursion Logic OOP AOP 2 What is func&onal programming It is NOT what you
More informationSorting. Task Description. Selection Sort. Should we worry about speed?
Sorting Should we worry about speed? Task Description We have an array of n values in any order We need to have the array sorted in ascending or descending order of values 2 Selection Sort Select the smallest
More informationCMSC 430 Introduction to Compilers. Fall Everything (else) you always wanted to know about OCaml (but were afraid to ask)
CMSC 430 Introduction to Compilers Fall 2015 Everything (else) you always wanted to know about OCaml (but were afraid to ask) OCaml You know it well from CMSC 330 All programming projects will be in OCaml
More informationCSCI 2041: Functions, Mutation, and Arrays
CSCI 2041: Functions, Mutation, and Arrays Chris Kauffman Last Updated: Fri Sep 14 15:06:04 CDT 2018 1 Logistics OCaml System Manual: 1.1-1.3 Practical OCaml: Ch 1-2 OCaml System Manual: 25.2 (Pervasives
More informationSorting Algorithms. + Analysis of the Sorting Algorithms
Sorting Algorithms + Analysis of the Sorting Algorithms Insertion Sort What if first k elements of array are already sorted? 4, 7, 12, 5, 19, 16 We can shift the tail of the sorted elements list down and
More informationLecture 2: Processes. CSE 120: Principles of Opera9ng Systems. UC San Diego: Summer Session I, 2009 Frank Uyeda
Lecture 2: Processes CSE 120: Principles of Opera9ng Systems UC San Diego: Summer Session I, 2009 Frank Uyeda Announcements PeerWise accounts are now live. First PeerWise ques9ons/reviews due tomorrow
More informationProblem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n.
Problem 5. Sorting Simple Sorting, Quicksort, Mergesort Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all 1 i j n. 98 99 Selection Sort
More informationCSE Opera,ng System Principles
CSE 30341 Opera,ng System Principles Lecture 5 Processes / Threads Recap Processes What is a process? What is in a process control bloc? Contrast stac, heap, data, text. What are process states? Which
More informationA Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1
A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed. 1 Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed. 2 Two Patterns
More informationCSE373: Data Structure & Algorithms Lecture 18: Comparison Sorting. Dan Grossman Fall 2013
CSE373: Data Structure & Algorithms Lecture 18: Comparison Sorting Dan Grossman Fall 2013 Introduction to Sorting Stacks, queues, priority queues, and dictionaries all focused on providing one element
More informationShell CSCE 314 TAMU. Functions continued
1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in
More informationQuick Sort. CSE Data Structures May 15, 2002
Quick Sort CSE 373 - Data Structures May 15, 2002 Readings and References Reading Section 7.7, Data Structures and Algorithm Analysis in C, Weiss Other References C LR 15-May-02 CSE 373 - Data Structures
More informationWe have the pointers reference the next node in an inorder traversal; called threads
Leaning Objective: In this Module you will be learning the following: Threaded Binary Tree Introduction: Threaded Binary Tree is also a binary tree in which all left child pointers that are NULL (in Linked
More informationCS 31: Intro to Systems Threading & Parallel Applications. Kevin Webb Swarthmore College November 27, 2018
CS 31: Intro to Systems Threading & Parallel Applications Kevin Webb Swarthmore College November 27, 2018 Reading Quiz Making Programs Run Faster We all like how fast computers are In the old days (1980
More informationCSE 373: Data Structure & Algorithms Comparison Sor:ng
CSE 373: Data Structure & Comparison Sor:ng Riley Porter Winter 2017 1 Course Logis:cs HW4 preliminary scripts out HW5 out à more graphs! Last main course topic this week: Sor:ng! Final exam in 2 weeks!
More informationCSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting. Aaron Bauer Winter 2014
CSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting Aaron Bauer Winter 2014 The main problem, stated carefully For now, assume we have n comparable elements in an array and we want
More information8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?
8/5/10 TODAY'S OUTLINE Recursion COMP 10 EXPLORING COMPUTER SCIENCE Revisit search and sorting using recursion Binary search Merge sort Lecture 8 Recursion WHAT DOES THIS CODE DO? A function is recursive
More informationComputer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Searching and Sorting
Computer Science 5 Problem Solving with Java The College of Saint Rose Spring 016 Topic Notes: Searching and Sorting Searching We all know what searching is looking for something. In a computer program,
More informationProcesses and Threads
COS 318: Operating Systems Processes and Threads Kai Li and Andy Bavier Computer Science Department Princeton University http://www.cs.princeton.edu/courses/archive/fall13/cos318 Today s Topics u Concurrency
More information(Today's lecture is not on the midterm)
Midterm on Wednesday of this week in class 3-4:20pm Tenta=ve loca=on: Friend 101 (we are s.ll checking... will no.fy on Piazza... will direct you on the day) Topics: Possibly revisi.ng ques.ons similar
More informationCSE 373: Data Structures and Algorithms
CSE 373: Data Structures and Algorithms Lecture 22: Introduction to Multithreading and Parallelism Instructor: Lilian de Greef Quarter: Summer 2017 Today: Introduction to multithreading and parallelism
More informationDivide and Conquer Sorting Algorithms and Noncomparison-based
Divide and Conquer Sorting Algorithms and Noncomparison-based Sorting Algorithms COMP1927 16x1 Sedgewick Chapters 7 and 8 Sedgewick Chapter 6.10, Chapter 10 DIVIDE AND CONQUER SORTING ALGORITHMS Step 1
More information61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013
61A LECTURE 22 TAIL CALLS, ITERATORS Steven Tang and Eric Tzeng July 30, 2013 Announcements Homework 12 due Thursday, not Monday. Take the time to get started on the project instead! Almost done with Scheme
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 7 January 30 th, 2015 Binary Search Trees (Lecture notes Chapter 7) ! Homework #1 feedback dope assignment, got a 96.4 the first time, careless mistake,
More informationCS1 Lecture 30 Apr. 2, 2018
CS1 Lecture 30 Apr. 2, 2018 HW 7 available very different than others you need to produce a written document based on experiments comparing sorting methods If you are not using a Python (like Anaconda)
More informationSearching and Sorting
CS 211 SEARCH & SORT SEARCHING & SORTING Searching and Sorting Searching means that we have some collection of data, and we seek a particular value that might be contained within our collection. We provide
More informationMERGESORT & QUICKSORT cs2420 Introduction to Algorithms and Data Structures Spring 2015
MERGESORT & QUICKSORT cs2420 Introduction to Algorithms and Data Structures Spring 2015 1 administrivia 2 -assignment 4 due tonight at midnight -assignment 5 is out -midterm next Tuesday 3 last time 4
More informationCon$nuing CPS. COS 326 David Walker Princeton University
Con$nuing CPS COS 326 David Walker Princeton University Last Time We saw that code like this could take up a lot of stack space: let rec sum_to (n:int) : int = if n > 0 then n + sum_to (n-1) else 0 Last
More informationCOMP2012H Spring 2014 Dekai Wu. Sorting. (more on sorting algorithms: mergesort, quicksort, heapsort)
COMP2012H Spring 2014 Dekai Wu Sorting (more on sorting algorithms: mergesort, quicksort, heapsort) Merge Sort Recursive sorting strategy. Let s look at merge(.. ) first. COMP2012H (Sorting) 2 COMP2012H
More informationUniversity of Washington What is a process?
What is a process? What is a program? A processor? A process? 1 What is a process? Why are we learning about processes? Processes are another abstrac'on in our computer system the process abstrac9on provides
More informationConcurrent Programming
Concurrent Programming 15-213 / 18-213: Introduc2on to Computer Systems 23 rd Lecture, Nov. 14, 2013 Instructors: Randy Bryant, Dave O Hallaron, and Greg Kesden 1 Concurrent Programming is Hard! The human
More informationSE350: Operating Systems. Lecture 3: Concurrency
SE350: Operating Systems Lecture 3: Concurrency Main Points Thread abstraction What are threads and what is the thread abstraction? Thread life cycle What states does a thread go through? Thread Implementation
More information(Sequen)al) Sor)ng. Bubble Sort, Inser)on Sort. Merge Sort, Heap Sort, QuickSort. Op)mal Parallel Time complexity. O ( n 2 )
Parallel Sor)ng A jungle (Sequen)al) Sor)ng Bubble Sort, Inser)on Sort O ( n 2 ) Merge Sort, Heap Sort, QuickSort O ( n log n ) QuickSort best on average Op)mal Parallel Time complexity O ( n log n ) /
More informationQuicksort. Repeat the process recursively for the left- and rightsub-blocks.
Quicksort As the name implies, this is the fastest known sorting algorithm in practice. It is excellent for average input but bad for the worst-case input. (you will see later). Basic idea: (another divide-and-conquer
More informationWhat is an algorithm?
/0/ What is an algorithm? Searching and Sorting (Savitch, Chapter 7.) TOPICS Algorithms Complexity Binary Search Bubble Sort Insertion Sort Selection Sort A finite set of precise instrucons for performing
More informationLecture 5: Concurrency and Threads
CS 422/522 Design & Implementation of Operating Systems Lecture 5: Concurrency and Threads Zhong Shao Dept of Computer Science Yale University Acknowledgement: some slides are taken from previous versions
More informationCS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics
CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics 1 Sorting 1.1 Problem Statement You are given a sequence of n numbers < a 1, a 2,..., a n >. You need to
More informationCSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes
CSE 250 Final Exam Fall 2013 Time: 3 hours. Dec 11, 2013 Total points: 100 14 pages Please use the space provided for each question, and the back of the page if you need to. Please do not use any extra
More informationAssignment 4: Question 1b omitted. Assignment 5: Question 1b clarification
Announcements Assignment 4: Question 1b omitted Assignment 5: Question 1b clarification /* initialize and keep track of the last processed element smaller than pivot; use the mid variable from lecture
More informationDivide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Instructor: X. Zhang
Divide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Instructor: X. Zhang Acknowledgement The set of slides have use materials from the following resources Slides for textbook by Dr. Y.
More informationDivide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Acknowledgement. Outline
Divide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Instructor: X. Zhang Acknowledgement The set of slides have use materials from the following resources Slides for textbook by Dr. Y.
More informationHabanero-Java Library: a Java 8 Framework for Multicore Programming
Habanero-Java Library: a Java 8 Framework for Multicore Programming PPPJ 2014 September 25, 2014 Shams Imam, Vivek Sarkar shams@rice.edu, vsarkar@rice.edu Rice University https://wiki.rice.edu/confluence/display/parprog/hj+library
More informationLecture 23: Parallelism. Parallelism Idea. Parallel Programming in Java. CS 62 Fall 2015 Kim Bruce & Michael Bannister
Lecture 23: Parallelism CS 62 Fall 2015 Kim Bruce & Michael Bannister Some slides based on those from Dan Grossman, U. of Washington Parallel Programming in Java Parallelism Idea Creating a thread: 1.
More informationLecture 29: Parallelism II
Lecture 29: Parallelism II CS 62 Spring 2019 William Devanny & Alexandra Papoutsaki Some slides based on those from Dan Grossman, U. of Washington 1 How to Create a Thread in Java 1. Define class C extends
More informationCS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1
CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 Goals of this tutorial You should be able to... understand
More informationSection. Announcements
Lecture 7 Section Announcements Have you been to section; why or why not? A. I have class and cannot make either time B. I have work and cannot make either time C. I went and found section helpful D. I
More informationCS Lecture 14: Hash tables. Prof. Clarkson Spring Today s music: Re-hash by Gorillaz
CS 3110 Lecture 14: Hash tables Prof. Clarkson Spring 2015 Today s music: Re-hash by Gorillaz Review Recently: Data abstractions Lists, stacks, queues, dictionaries, polynomials,... Imperative features
More informationCS 5614: (Big) Data Management Systems. B. Aditya Prakash Lecture #5: Hashing and Sor5ng
CS 5614: (Big) Data Management Systems B. Aditya Prakash Lecture #5: Hashing and Sor5ng (Sta7c) Hashing Problem: find EMP record with ssn=123 What if disk space was free, and 5me was at premium? Prakash
More informationSome Advanced ML Features
Some Advanced ML Features Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming University of Washington: Dan Grossman ML is small Small number of powerful constructs
More informationWhat next? CSE332: Data Abstractions Lecture 20: Parallel Prefix and Parallel Sorting. The prefix-sum problem. Parallel prefix-sum
What next? CSE332: Data Abstractions Lecture 20: Parallel Prefix and Parallel Sorting Dan Grossman Spring 2010 Done: Simple ways to use parallelism for counting, summing, finding Even though in practice
More informationFunc%onal Decomposi%on
Func%onal Decomposi%on COS 326 David Walker Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel permission granted to reuse these slides for non-commercial educa%onal purposes
More informationLecture 6: Sequential Sorting
15-150 Lecture 6: Sequential Sorting Lecture by Dan Licata February 2, 2012 Today s lecture is about sorting. Along the way, we ll learn about divide and conquer algorithms, the tree method, and complete
More informationLecture 2: Memory in C
CIS 330:! / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 2:
More informationDivide and Conquer 4-0
Divide and Conquer 4-0 Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances recursively 3. Obtain
More informationLecture 7. Transform-and-Conquer
Lecture 7 Transform-and-Conquer 6-1 Transform and Conquer This group of techniques solves a problem by a transformation to a simpler/more convenient instance of the same problem (instance simplification)
More informationMutation. COS 326 Andrew W. Appel Princeton University. slides copyright David Walker and Andrew W. Appel
Mutation COS 326 Andrew W. Appel Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel Mutation? 2 Reasoning about Mutable State is Hard mutable set insert i s1; f x; member
More informationFrom Processes to Threads
From Processes to Threads 1 Processes, Threads and Processors Hardware can interpret N instruction streams at once Uniprocessor, N==1 Dual-core, N==2 Sun s Niagra T2 (2007) N == 64, but 8 groups of 8 An
More informationLab 9: More Sorting Algorithms 12:00 PM, Mar 21, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Lab 9: More Sorting Algorithms 12:00 PM, Mar 21, 2018 Contents 1 Heapsort 2 2 Quicksort 2 3 Bubble Sort 3 4 Merge Sort 3 5 Mirror Mirror
More informationCOSC242 Lecture 7 Mergesort and Quicksort
COSC242 Lecture 7 Mergesort and Quicksort We saw last time that the time complexity function for Mergesort is T (n) = n + n log n. It is not hard to see that T (n) = O(n log n). After all, n + n log n
More informationLast time: generic programming
1/ 55 Last time: generic programming val (=) : { D: DATA } D. t D. t bool 2/ 55 This time: monads etc., continued >>= effect E 3/ 55 Recap: monads, bind and let An imperative program let id =! counter
More informationO(n): printing a list of n items to the screen, looking at each item once.
UNIT IV Sorting: O notation efficiency of sorting bubble sort quick sort selection sort heap sort insertion sort shell sort merge sort radix sort. O NOTATION BIG OH (O) NOTATION Big oh : the function f(n)=o(g(n))
More informationCS-141 Final Exam Review December 16, 2015 Presented by the RIT Computer Science Community
CS-141 Final Exam Review December 16, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu Python Basics 1. Although most in the industry will be reasonably forgiving when it comes
More informationRecap: ML s Holy Trinity. Story So Far... CSE 130 Programming Languages. Datatypes. A function is a value! Next: functions, but remember.
CSE 130 Programming Languages Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Datatypes Compile-time Static Types Ranjit Jhala UC San Diego 1. Programmer enters expression
More informationSolution to CSE 250 Final Exam
Solution to CSE 250 Final Exam Fall 2013 Time: 3 hours. December 13, 2013 Total points: 100 14 pages Please use the space provided for each question, and the back of the page if you need to. Please do
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques () Lecture 12 February 7, 2018 Partiality, Sequencing, Records Chapters 12, 13 Midterm 1 This Friday in class Review session Tonight, 6 7:30 PM DRLB A1 Announcements
More informationCSE 130 Programming Languages. Datatypes. Ranjit Jhala UC San Diego
CSE 130 Programming Languages Datatypes Ranjit Jhala UC San Diego Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression
More informationImperative programming in F#
Imperative programming in F# Björn Lisper School of Innovation, Design, and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ Imperative programming in F# (revised 2015-05-05)
More informationHaske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell
Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program
More informationFunctional Programming. Pure Functional Programming
Functional Programming With examples in F# Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands. Computation is largely performed by applying
More informationW4118 Operating Systems. Junfeng Yang
W4118 Operating Systems Junfeng Yang What is a process? Outline Process dispatching Common process operations Inter-process Communication What is a process Program in execution virtual CPU Process: an
More informationLecture 6 Sorting and Searching
Lecture 6 Sorting and Searching Sorting takes an unordered collection and makes it an ordered one. 1 2 3 4 5 6 77 42 35 12 101 5 1 2 3 4 5 6 5 12 35 42 77 101 There are many algorithms for sorting a list
More informationConcurrent programming
Concurrent programming : Introduc2on to Computer Systems 24th Lecture Sec2ons 12.1-12.3 Instructors: Ian Foster Gordon Kindlmann Slides borrow copiously from materials by Randy Bryant and Dave O Hallaron
More information1 Splay trees. 2 Implementation of splay. CS134b Homework #1 January 8, 2001 Due January 15, 2001
CSb Homework # January, 00 Due January, 00 Splay trees One of the most important data structures used in compilers are sets and tables of arbitrary elements. For example, when we do type checking, we will
More information