- 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.
- SQL Server 2016 數據庫教程(第4版)
- 云計算環境下的信息資源集成與服務
- 從0到1:數據分析師養成寶典
- Oracle RAC 11g實戰指南
- PySpark大數據分析與應用
- 大數據:規劃、實施、運維
- 一個64位操作系統的設計與實現
- 圖數據實戰:用圖思維和圖技術解決復雜問題
- Oracle RAC日記
- 數據科學實戰指南
- Mastering LOB Development for Silverlight 5:A Case Study in Action
- 貫通SQL Server 2008數據庫系統開發
- 大數據技術原理與應用:概念、存儲、處理、分析與應用
- Expert Python Programming(Third Edition)
- 利用Python進行數據分析(原書第2版)