This is the archived Fall 2013 version of the course.
For the most recent version, see http://rust-class.org/class-13-reflections-on-rusting-rust.html.

Class 13: Reflections on Rusting Rust?

Action Items

The midterm exam is posted: http://goo.gl/0HsRwI. It is due on Monday, 14 October (11:59pm). The exam is open resources, other than other humans. You may not discuss anything relevant to the exam with any other human (other than the course staff) between now and the deadline.

Problem Set 3 is due Monday, 28 October. PS3 is more challenging than PS2, and provides many opportunities for doing exciting things beyond the minimum acceptable solution. You will be much happier later if you start it now.

Semaphore

This is an incorrect attempt to implement a semaphore (unsafely).

// semaphore.rs - Implementing a Semaphore

type Semaphore = Option<uint> ; // either None (available) or owner

static mut count: uint = 0; // protected by lock
static mut lock: Semaphore = None; 

fn grab_lock(id: uint) {
    unsafe {
        while (lock.is_some()) {
            ; // wait for lock 
        }
        lock = Some(id);
    }
}

fn release_lock() {
    unsafe {
        lock = None;
    }
}

fn update_count(id: uint) {
    unsafe {
        grab_lock(id);
        count += 1;
        println(fmt!("Count updated by %?: %?", id, count));
        release_lock();
    }
}

fn main() {
    for num in range(0u, 10) {
        do spawn {
            for _ in range(0u, 1000) {
                update_count(num);
            }
        }
    }
}

Why doesn't it work?

What would be necessary to implement mutual exclusion correctly using a sempahore?

Links

Ken Thompson, Reflections on Trusting Trust (1983 Turing Award Acceptance Speech)

Edsger W. Dijkstra, Communicating Sequential Processes (transcript)