提问
当在派生线程中创建Box
时,Box
的地址非常高,这是典型的堆栈地址,但Box
应该指向堆。地址为什么这么高?
代码
use std::thread;
use std::time::Duration;
fn main() {
let x = 42;
println!("x (main thread, stack): {:p}", &x);
println!("Box (main thread, heap): {:p}", Box::new(x));
thread::spawn(|| {
let x = 42;
println!("x (spawned thread, stack): {:p}", &x);
println!("Box (spawned thread, heap): {:p}", Box::new(x));
});
thread::sleep(Duration::from_secs(1)); // Give the spawned thread some time
}
字符串
输出
x (main thread, stack): 0x7fff1d0cb414
Box (main thread, heap): 0x55e608db8ae0
x (spawned thread, stack): 0x7f94ae707b54
Box (spawned thread, heap): 0x7f94a8000b80
型
环境
- Linux操作系统
- 货物1.69.0
- 下载rustc 1.69.0
1条答案
按热度按时间ulmd4ohb1#
第二对地址相距103 MiB,远远超过了派生线程的2 MiB堆栈大小,因此两个框都不会分配任何堆栈附近的任何位置。除此之外,确切的内存位置是实现细节。