Lecture 8 Notes

# Lecture 8 Notes

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: egin if m[n] = -1 then m[n] = fib(n-1) + fib(n-2) return m[n] end Now the call graph of fib(5) looks like the following. The memoization technique saves the intermediate Fibonacci numbers while calculating, resulting fewer fib(n) calls. fib(5) fib(4) fib(3) fib(3) fib(2) fib(2) fib(1) fib(1) fib(0) (6) Express the recursive relation bottom­up. function fib(n) begin if n = 0 then return 0 else if n = 1 then return 1 else begin var f = {0, 1, …} for i = 2 to n begin f[i] = f[i-1] + f[i-2] end return f[n] end end The bottom‐up version fills up an array from the bottom (i.e. fib(0), fib(1)) to the top (i.e. fib(n)). The Fibonacci number example describes different approaches for the dynamic programming pattern; a top‐down approach using divide‐and‐conquer with and without memoization and a bottom‐up approach. (7) Parallelize. Let’s use the top‐down expressed Fibonacci implementation in (4). We could use the push method or pull method to communicate between the parent and the child. Let’s start with the push method. The first version is expressed in Clik. The second version is expressed using atomic add, and thread primitives. function fib(n) begin if n = 0 then return 0 else if n = 1 then return 1 else begin value = spawn(fib(n-1)) + spawn(fib(n-2)) sync return value end end function fib(value, n) begin // value is call by reference var local = 0 if n = 0 then begin local = 0 end else if n = 1 then begin local = 1 end else begin create thread fib(local, n-1) as t1 create thread fib(local, n-2) as t2 join t1, t2 end atomicadd(value, local) end If it were expressed in a pull fashion, it would look like the following. It defines a flag that the parent could poll to check whether the child has completed its computation or not. Each child has its local storage to store the computation result that the parent could read in the future. function fib(n) begin if n = 0 then begin local storage = 0 mark completed flag end else if n = 1 then begin local storage = 1 mark completed flag end else begin create thread fib(n-1) as t1 create thread fib(n-2) as t2 poll completed flag o...
View Full Document

## This document was uploaded on 03/17/2014 for the course CS 4800 at Northeastern.

Ask a homework question - tutors are online