Commit c10a7057 authored by Ralf Jung's avatar Ralf Jung
Browse files

factor init function out; separate file for paper example

parent 13d78376
Pipeline #42455 passed with stage
in 22 minutes and 54 seconds
......@@ -9,22 +9,26 @@ fn print_list<'id, T: fmt::Debug>(tag: char, list: &NodePtr<'id, T>, token: &Gho
}
}
fn init_list<'id>(token: &mut GhostToken<'id>, list_size: u32) -> (NodePtr<'id, u32>, NodePtr<'id, u32>) {
let head: NodePtr<u32> = Node::alloc(Node::new(0));
let mut tail = Some (head.clone());
// To append to the list, we need a &mut GhostToken
for i in 1..list_size {
let node = Node::alloc(Node::new(i));
Node::insert_next(tail.take().unwrap(), &node, token);
tail = Some(node);
};
(head, tail.unwrap())
}
fn main() {
GhostToken::new(|mut token| {
let list_size = 50;
// Allocate a list from 0 to list_size - 1
let list: NodePtr<u32> = Node::alloc(Node::new(0));
let mut tail = Some (list.clone());
// To append to the list, we need a &mut GhostToken
(1..list_size).for_each(|i| {
let node = Node::alloc(Node::new(i));
Node::insert_next(tail.take().unwrap(), &node, &mut token);
tail = Some(node);
});
let tail = tail.unwrap();
let (list, tail) = init_list(&mut token, list_size);
// Print the list we created
print!("Numbers: ");
......
use ghostcell::dlist_arc::*;
use ghostcell::GhostToken;
use std::sync::RwLock;
use std::{fmt, thread, time};
fn print_list<'id, T: fmt::Debug>(tag: char, list: &NodePtr<'id, T>, token: &GhostToken<'id>) {
for d in Node::iter(list, token) {
print!("{}{:?}, ", tag, d);
}
}
fn init_list<'id>(token: &mut GhostToken<'id>, list_size: u32) -> NodePtr<'id, u32> {
let head: NodePtr<u32> = Node::alloc(Node::new(0));
let mut tail = Some(head.clone());
// To append to the list, we need a &mut GhostToken
for i in 1..list_size {
let node = Node::alloc(Node::new(i));
Node::insert_next(tail.take().unwrap(), &node, token);
tail = Some(node);
}
head
}
fn main() {
GhostToken::new(|mut token| {
// Allocate a list of size 50.
let list = init_list(&mut token, 50);
rayon::join(
|| Node::iter_immut(&list, &token, |n| print!("{:?}, ", n)),
|| Node::iter_immut(&list, &token, |n| print!("{:?}, ", n)),
);
// We can put a RwLock on the token to allow concurrent writes and reads.
let lock_token: RwLock<GhostToken> = RwLock::new(token);
// The read may come in before or after the write.
// If the read comes in later, it should print the updated data.
rayon::join(
// fork two child threads
|| {
let token: &GhostToken = &lock_token.read().unwrap(); // acquire read lock
Node::iter_immut(&list, token, |n| print!("{:?}, ", n));
},
|| {
let token: &mut GhostToken = &mut lock_token.write().unwrap(); // acquire write lock
Node::iter_mut(&list, token, |n| *n += 100); // add 100 to the nodes' data
},
);
});
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment