- 主题:rust新手问一下
Rust 标准库 1.63 增加了一个期待已久的功能:scoped thread(作用域线程)。
fn main() {
println!("Hello, world!");
use std::thread;
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
let v1 = &vals[0];
use crossbeam_channel::unbounded;
// Create a channel of unbounded capacity.
let (tx, rx) = unbounded::<&String>();
let mut a = vec![1, 2, 3];
let mut x = 0;
thread::scope(|s| {
s.spawn( || {
println!("hello from the first scoped thread");
// borrow `a` here
dbg!(&a);
for word in &vals {
tx.send(word);
}
});
s.spawn( || {
println!("hello from the second scoped thread");
// mutably borrow `x`, because no other threads are using it
x += a[0] + a[2];
for recv in rx {
println!("Got: {}", recv);
}
});
println!("hello from the main thread");
});
// after the scope, can modify and access the variables again
a.push(4);
assert_eq!(x, a.len());
}
【 在 z16166 的大作中提到: 】
: 给send()传递ref是不行的,因为这个ref是在发送线程(或者说负责发送的闭包)里的,
: 一旦发送线程结束(或者说发送的闭包销毁了),ref即失效,此后接收线程收到这个ref后就是dangling reference。
: 这样去掉for带来的问题后,也是报错:
: ...................
--
FROM 117.147.20.*
哈哈,第三方库都搞这么久了,才加入
现在知道这些都是用unsafe来绕过编译器safe检查了,反正码农保证安全。
【 在 txgx 的大作中提到: 】
: Rust 标准库 1.63 增加了一个期待已久的功能:scoped thread(作用域线程)。
: fn main() {
: println!("Hello, world!");
: ...................
--
FROM 60.12.138.*
这么久了还是unsafe的吗?没扒进去看。
【 在 z16166 的大作中提到: 】
: 哈哈,第三方库都搞这么久了,才加入
:
: 现在知道这些都是用unsafe来绕过编译器safe检查了,反正码农保证安全。
: --
发自「今日水木 on PBCM10」
--
FROM 117.147.20.*
这是属于只能用unsafe来绕过编译器的检查的。unsafe用得最多的应该是std::mem::transmute
【 在 txgx 的大作中提到: 】
: 这么久了还是unsafe的吗?没扒进去看。
: 发自「今日水木 on PBCM10」
--
FROM 60.12.138.*
await前后,根据具体runtime的要求,可能是跨线程执行的
跨线程的话,要求rc必定是Send,否则就违反了规则
当然,这里可能是没问题的,但目前rust的生命周期检测无法涵盖这种情况
【 在 txgx 的大作中提到: 】
: 大概是明白了,rust担心rc被其他人使用,所以用规则一棍子打死。
: !send的不能穿越await
: 就是懒政。
: ...................
--
FROM 123.112.18.*
这个就是所有权转移到函数里了,外面不可见了...
如果需要的话,可能会返回一个Self,可能是修改后的实例或创建的新实例
嗯,感觉你需要先看下书,这个是比较简单的情况
【 在 txgx 的大作中提到: 】
: self的ownership发生了转移,所以是mut self。
: 这个怎么理解,哪本书里面有解释?
: 发自「今日水木 on MRX-W29」
--
FROM 123.112.18.*
原来36楼大牛己经讲过了。估计这个unsafe是不可避免的。
【 在 z16166 的大作中提到: 】
: 这是属于只能用unsafe来绕过编译器的检查的。unsafe用得最多的应该是std::mem::transmute
: --
发自「今日水木 on PBCM10」
--
FROM 117.147.20.*