We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
解决的办法也很简单(理论上):
不共享数据就是**不要在多线程中共享变量,
Rust对此在编译器做了保证,防止不共享的变量被共享了,而这靠的就是Send trait。
Send在多线程程序中起到了什么作用呢?满足Send,说明这个变量可以安全的在线程间转移。
实现了Send trait表示是所有权类型
不共享数据的时候,我们可以直接将变量move给生成的线程,这样,数据就被这个线程独有了。比如
let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); handle.join().unwrap();
vector v
handle.join().unwrap()
Rc<i32>
满足Send约束的类型,能在多线程之间安全的排它使用(Exclusive access is thread-safe),所有权类型
Send
满足Send约束的类型T,表示T和&mut T(mut表示能修改这个引用,甚至于删除即drop这个数据)这两种类型的数据能在多个线程之间传递
T
&mut T
mut
drop
move
RefCell<usize>
Mutex<RefCell<usize
sd::sync::Arc
std::sync::Mutex
std::sync::RwLock
Sync
&T
T: Sync ≡ &T: Send
i32
什么是'static的生命周期呢?
#rust #public
The text was updated successfully, but these errors were encountered:
No branches or pull requests
参考资料
如何保证共享数据多线程安全
解决的办法也很简单(理论上):
共享只读数据
(concept:: Sync 和 Send, 'static))
Send
不共享数据就是**不要在多线程中共享变量,
Rust对此在编译器做了保证,防止不共享的变量被共享了,而这靠的就是Send trait。
Send在多线程程序中起到了什么作用呢?满足Send,说明这个变量可以安全的在线程间转移。
实现了Send trait表示是所有权类型
不共享数据的时候,我们可以直接将变量move给生成的线程,这样,数据就被这个线程独有了。比如
vector v
在主线程创建以后,直接move给了生成的线程,那么除了那个线程,没有其他的地方可以使用这个vector。handle.join().unwrap()
)前面尝试打印vector,Rust就会报错Rc<i32>
不能 send 在threads safelySend:
满足
Send
约束的类型,能在多线程之间安全的排它使用(Exclusive access is thread-safe),所有权类型满足
Send
约束的类型T
,表示T
和&mut T
(mut
表示能修改这个引用,甚至于删除即drop
这个数据)这两种类型的数据能在多个线程之间传递move
值以及修改引用到的值。Sync
RefCell<usize>
改成Mutex<RefCell<usize
>>sd::sync::Arc
、std::sync::Mutex
、std::sync::RwLock
等Sync
约束的类型,能在多线程之间安全的共享使用(Shared access is thread-safe)。Sync
约束的类型T
,只表示该类型能在多个线程中读共享,即:不能move
,也不能修改,仅仅只能通过引用&T
来读取这个值。Send
约束的条件下,类型T才能满足Sync
约束 (a type T is Sync if and only if &T is Send)。即:T: Sync ≡ &T: Send
。i32
类型,大多是同时满足Send
和Sync
这两个约束的,因为这些类型的共享引用(&)既能在多个多个线程中使用。'static
什么是'static的生命周期呢?
#rust #public
The text was updated successfully, but these errors were encountered: