#Closures
1 messages · Page 1 of 1 (latest)
recall that closures are just anonymous structs
imagine something like ```rust
struct Closure<'a> {
capture: &'a mut String,
}
impl Closure<'_> {
fn call(&self) {
println!("{:?}", self.capture.pop())
}
}
that obviously can't work because it's being borrowed as &self
yup
its pretty easy once you get it
it probably spawns some of them before the first one has actually started running code
you dont have any guarantees about execution order unless you join on the handle or use barriers etc
You cant predict that. If you spawn a new thread a completly new execution context branching from the main thread. You can imagine throwing marbles down a slope. You can throw them one after the other, but it depends on the marble when it finishes. You can ofc wait on one marble to reach the bottom before throwing the next (by joining the thread again)
it uses OS specific tools to check in a busy loop or asks the os to be woken up again when the thread finishes
join() will block until the closure of spawn returns
you can see that the thread never terminates. so the join never really finishes
fn main() {
let handle = std::thread::spawn(||{ loop {}; 42 });
let y = handle.join().unwrap();
println!("{y}");
}```
you can use godbolt to see the asm
?godbolt ```rs
#[no_mangle]
pub fn foo() -> u64 {
(0u64..1000u64).sum()
}
foo:
mov eax, 499500
ret
Missing code block. Please use the following markdown:
`code here`
or
`[0m`[0m`rust
code here
`[0m`[0m`
[0m[1m[33mwarning[0m[0m[1m: function `main` is never used[0m
[0m [0m[0m[1m[38;5;12m--> [0m[0m<source>:1:4[0m
[0m [0m[0m[1m[38;5;12m|[0m
[0m[1m[38;5;12m1[0m[0m [0m[0m[1m[38;5;12m|[0m[0m [0m[0mfn main() {[0m
[0m [0m[0m[1m[38;5;12m|[0m[0m [0m[0m[1m[33m^^^^[0m
[0m [0m[0m[1m[38;5;12m|[0m
[0m [0m[0m[1m[38;5;12m= [0m[0m[1mnote[0m[0m: `#[warn(dead_code)]` on by default[0m
[0m[1m[33mwarning[0m[0m[1m: 1 warning emitted[0m
```No output. Consider adding `#[no_mangle]` before your functions.
it doesn't do main(), only pub fns
i dont think assembly will help much here. it will just call some platform specific function for spawning threads