CS 111 Lecture 8 Scribe Notes - Fall 2013

Prepared by Hee Hwang, for a lecture given by Paul Eggert at UCLA on October 23, 2013.



Multithreaded ray tracer(8 threads)

double space[1000][1000][1000] 
space[i][j][k] = 10;

[Problem]

Changes aren't done atomically. = Other threads can see partial changes

space[i][j][k] = 0.5
space[i][j][k+1] = 0.5

[Solution]


Bill Gates's Bank Account

int balance; // Dr. Eggert's balance in pennies.
// Dr. Eggert's maximum: 2^31-1: Roughly 20 million
long long int balance; // Bill Gates' balance in pennies.
// Bill Gates's maximum: 2^63-1

[Case 1]

What if he put more than 2^63-1?

Bank: Sorry, Bill Gates. Your balance is negative since you put too much money.

How to detect integer overflow?

gcc .ftrapv // if there is a signed integer overflow, crash it.
bool deposit(long long int amount){
if(amt < 0) return 0;;
if(amt > LLONGMAX-balance) return 0;
balance += amount;
return 1;
}
bool withdraw (long long int amount){ 
if(amt < 0) return 0;
if(amt >balance) return 0;
balance -= amount;
return 1;
}

[Case2]

What if two people are trying to withdraw money?

Problem: You will get negative amount of the money

[Solution]

long long b = balance
if(amount > b)
balance = b-amount;
transfer(amount, acct1, acct2){
}

Example:


Terminology


Pipe Implementation with Lock

It needs to be synchronized since one file is reading and one file is writing

// Read and write only one byte 
enum { EMPTY = CHAR_MAX+1 }; 
enum N = 1024;
struct pipe{
    char buf[N];
    unsigned r, w; 
}

R => ----------------------------------------- <= W

read starts from the left and write starts from the right

bool writec(struct pipe *p, char c){
    int ret;
    lock(&l);
    if(p->w - p->r == N) ret = 0;
    p->buf[p->w++ %N] = c;
    ret = 1;
    unlock(&l)
    return ret;
}
int readc(struct pipe *p){
    int r;
    lock(&l).;
    if(p->w == p->r) r = empty; // if writing amount is reading amount.
    int ret = p->buf[p->r++%N];
    unlock(&l);
    return ret;
}

[Problem 1] "W" thinks the pipe is empty, but it could be full.

[Solution 1] Use a lock and unlock!

lock(&l); 
unlock(&l);

[Precondition 1]

[Precondition 2]

[Problem 2]

[Solution 2]


[Problem 3]

[Solution 3]

enum { EMYPTY=CHAR_MAX+1 }
enum{n = 1024};
struct pipe{
    lock l;
    char buf[N]; 
    unsigned int r, w; 
} 
writec(struct pipe, char c)

Critical Section