Skip to content

Instantly share code, notes, and snippets.

@bblum
Created September 3, 2012 18:42
Show Gist options
  • Select an option

  • Save bblum/3612070 to your computer and use it in GitHub Desktop.

Select an option

Save bblum/3612070 to your computer and use it in GitHub Desktop.
for digitalknight, a scheme of how to spawn a global memory watcher task.
fn send_message_to_memory_watcher() {
// this is code that all tasks will run
let chan = get_memory_watcher_chan();
chan.send(...message...);
}
fn get_memory_watcher_chan() -> shared_chan<MemoryWatcherMessage> {
let shared_chan_ptr = rustrt::get_global_shared_chan_ptr();
// Double-check locking. (look this up on wikipedia if you don't know what
// it means)
if shared_chan_ptr.is_null() {
// No shared channel exists yet. Prepare to try to create it.
let (chan,port) = pipes::stream();
let my_shared_chan = ~pipes::SharedChan(chan);
if compare_and_swap(shared_chan_ptr, // destination address
ptr::null(), // expected value
my_shared_chan // new value
) {
// We were the first task to do this. We have to initialise.
// Future tasks that read from the shared chan ptr will see the
// value that we just stored in there.
task::task().unlinked().spawn_with(port, memory_watcher_task);
return my_shared_chan;
} else {
// We raced with somebody else, who got in first. Same as the fast
// path below.
return *shared_chan_ptr;
}
} else {
// Fast-path. No need to do anything.
return *shared_chan_ptr;
}
}
fn memory_watcher_task(msg_port: pipes::Port<MemoryWatcherMessage>) {
do priv::weaken_atsk |weak_po| {
// see https://github.com/mozilla/rust/blob/incoming/src/libcore/os.rs#L185
// for an example of what to do here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment