



























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




























2
cilk n1 = spawn fib(n-1); n2 = spawn fib(n-2); sync; int fib(int n) { if (n < 2) return n; else { int n1, n2; n1 = fib(n-1); n2 = fib(n-2); return (n1 + n2); } } 4
5
7
Legend continuation spawn return each circle represents a thread A B C continuation fib(4) A fib(1) A fib(0) A fib(1) A fib(0) A B C fib(2) A B C fib(3) A B C fib(2) A fib(1) spawn return
8
10
11
cilk int main(int argc, char *argv[]) { int n; double result; n = atoi(argv[1]); if (n <= 0) { printf(“'n = %d': ” “n must be positive\n”,n); } else { result = spawn sum(1, n); sync; printf("Result: %lf\n", result); } return 0; } #include <stdlib.h> #include <stdio.h> #include <cilk.h> cilk double sum(int L, int U) { if (L == U) return L; else { double lower, upper; int mid = (U+L)/2; lower = spawn sum(L, mid); upper = spawn sum(mid+ 1, U); sync; return (lower + upper); } }
13
14
—92 distinct solutions —12 unique solutions; others are rotations & reflections Image credit: http://en.wikipedia.org/wiki/Eight_queens_puzzle
16 cilk void nqueens(n, j, placement) { // precondition: placed j queens so far if (j == n) { /* found a placement */ process placement; return; } for (k = 1; k <= n; k++) if putting j+1 queen in k th position in row j+1 is legal copy placement into newplacement and add extra queen spawn nqueens(n,j+1,newplacement) sync discard placement }
Issues regarding placements —how can we report placements? —what if a single placement suffices? —no need to compute all legal placements —so far, no way to terminate children exploring alternate placement
17
19
read x read x add 1 add 1 write x write x one interleaving f returns 1!
20 Erroneous Parallel N Queens Solution Sketch cilk void nqueens(n, j, placement) { // precondition: placed j queens so far if (j == n) { /* found a placement */ process placement; return; } for (k = 1; k <= n; k++) if putting j+1 queen in k th position in row j+1 is legal place j+1 queen in k th position in row j+1 in placement spawn nqueens(n, j+1,placement) remove queen in k th position in row j+1 in placement sync }