- 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.
- 數(shù)據(jù)存儲(chǔ)架構(gòu)與技術(shù)
- Word 2010中文版完全自學(xué)手冊(cè)
- Google Visualization API Essentials
- PySpark大數(shù)據(jù)分析與應(yīng)用
- Lean Mobile App Development
- Creating Dynamic UIs with Android Fragments(Second Edition)
- Learning Proxmox VE
- SQL優(yōu)化最佳實(shí)踐:構(gòu)建高效率Oracle數(shù)據(jù)庫(kù)的方法與技巧
- 深入淺出 Hyperscan:高性能正則表達(dá)式算法原理與設(shè)計(jì)
- Oracle 11g+ASP.NET數(shù)據(jù)庫(kù)系統(tǒng)開發(fā)案例教程
- Deep Learning with R for Beginners
- 數(shù)據(jù)庫(kù)原理與設(shè)計(jì)實(shí)驗(yàn)教程(MySQL版)
- Oracle 11g數(shù)據(jù)庫(kù)管理與開發(fā)基礎(chǔ)教程
- 數(shù)字化轉(zhuǎn)型方法論:落地路徑與數(shù)據(jù)中臺(tái)
- 數(shù)據(jù)分析方法及應(yīng)用:基于SPSS和EXCEL環(huán)境