- Hands-On Data Structures and Algorithms with Rust
- Claus Matzinger
- 474字
- 2021-07-02 14:11:43
Moving data
The introductory snippet showed code that spawns a thread but did not pass any data into the scope. Just like any other scope, it requires either ownership of a value or at least a borrowed reference in order to work with that data. In this case, passing ownership is what we want, something that is called moving data into the scope.
If we change the snippet from the introduction to include a simple variable to print from within the thread, compilation is going to fail:
use std::thread;
fn threading() {
let x = 10;
let handle = thread::spawn(|| {
println!("Hello from a thread, the number is {}", x);
});
handle.join().unwrap();
}
The reason for this is simple: the compiler cannot determine the lifetimes of each of the scopes (will x still be there when the thread needs it?), so it refuses to compile the code:
Compiling ch1 v0.1.0 (file:///code/ch1)
error[E0373]: closure may outlive the current function, but it borrows `x`, which is owned by the current function
--> src/main.rs:5:32
|
5 | let handle = thread::spawn(|| {
| ^^ may outlive borrowed value `x`
6 | println!("Hello from a thread, the number is {}", x);
| - `x` is borrowed here
help: to force the closure to take ownership of `x` (and any other referenced variables), use the `move` keyword
|
5 | let handle = thread::spawn(move || {
| ^^^^^^^
As the compiler messages indicate, adding the move keyword will solve the issue! This keyword lets a thread pass ownership to a different thread; it "moves" the memory area:
fn threading() {
let x = 10;
let handle = thread::spawn(move || {
println!("Hello from a thread, the number is {}", x);
});
handle.join().unwrap();
}
When running this snippet, the output is as follows:
Hello from a thread, the number is 10
However, for passing multiple messages into a thread or implementing an actor model, the Rust standard library offers channels. Channels are single-consumer, multi-producer queues that let the caller send messages from multiple threads.
This snippet will spawn 10 threads and have each send a number into the channel, where it will be collected into a vector after the senders have finished executing:
use std::sync::mpsc::{channel, Sender, Receiver};
fn channels() {
const N: i32 = 10;
let (tx, rx): (Sender<i32>, Receiver<i32>) = channel();
let handles = (0..N).map(|i| {
let _tx = tx.clone();
thread::spawn(move || {
// don't use the result
let _ = _tx.send(i).unwrap();
})
});
// close all threads
for h in handles {
h.join().unwrap();
}
// receive N times
let numbers: Vec<i32> = (0..N).map(|_|
rx.recv().unwrap()
).collect();
println!("{:?}", numbers);
}
As expected, the output is as follows:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
With these tools, a multithreaded application can move data between threads without the need for manual locking or the dangers of inadvertently creating side effects.
- 數據存儲架構與技術
- LibGDX Game Development Essentials
- Hands-On Data Structures and Algorithms with Rust
- Greenplum:從大數據戰略到實現
- Python絕技:運用Python成為頂級數據工程師
- PySpark大數據分析與應用
- 數據化網站運營深度剖析
- 數據驅動設計:A/B測試提升用戶體驗
- Hadoop 3.x大數據開發實戰
- 一個64位操作系統的設計與實現
- Mastering LOB Development for Silverlight 5:A Case Study in Action
- 區塊鏈技術應用與實踐案例
- 貫通SQL Server 2008數據庫系統開發
- 數據庫與數據處理:Access 2010實現
- R Machine Learning Essentials