33 ms·
Yes, there was: the function was calling the passed in closure from a different thread. It is just one thread that’s actually appending to the Vec, but it’s st
by Cyph0n 6y ago
Yes, there was: the function was calling the passed in closure from a different thread.
It is just one thread that’s actually appending to the Vec, but it’s still a multi-threaded example.
- fulafel 6y agoAre we talking about the same example? struct Database { data: Vec<i32> } impl Database { fn store(&mut self, data: i32) { self.data.push(data); } } fn main() { let mut db = Database { data: vec![] }; do_work_and_then(|meaning_of_life| { println!("oh man, I found it: {}", meaning_of_life); db.store(meaning_of_life); }); // I'd read from `db` here if I really were making a web server. // But that's beside the point, so I'm not going to. // (also `db` would have to be wrapped in an `Arc<Mutex<T>>`) thread::sleep_ms(2000); } No threads are spawned.
- valand 6y ago` fn do_work_and_then(func: fn(i32)) { thread::spawn(move || { // Figuring out the meaning of life... thread::sleep_ms(1000); // gee, this takes time to do... // ah, that's it! let result: i32 = 42; // let's call the `func` and tell it the good news... func(result) }); } ` you missed a snippet, a thread is spawned. edit: formatting
- imtringued 6y agoIf for some magic reason thread::sleep_ms(1000) takes longer than 2000ms the main function would reach its end and deallocate the closure that is about to get called. Basically use after free.
- richardwhiuk 6y agoAnd that's possible, because the sleep call is a suggestion, not a guarantee. If the CPU is blocked for 2s, then the order of waking the threads is undetermined, and the race will occur.
- deleted 6y ago[deleted]
- mav3rick 6y agoThat is technically a race (sure) but at that point the program is getting killed anyway. Agree on the overall point though. I am a big fan of moving complete ownership / lifetime. It just makes things easier to reason about. In Chromium weak pointers are used to solve this use after free problem.
- filleduchaos 6y agoThe `do_work_and_then` function does spawn a thread, it's one of the first things established in the article.
- fulafel 6y agoAh, I thought it just named a block, my mistake.
- deleted 6y ago[deleted]