Rust के महत्वपूर्ण विषय
Rust Threads: spawn and join
Run code in parallel with thread::spawn and collect each result with join.
आप क्या सीखेंगे
- thread::spawn
- move closures
- join and return values
Three workers
- 1
spawn x3threads start - 2
sumeach works alone - 3
join()wait for each - 4
resultsprinted in order
Work that runs at the same time
A thread runs a piece of code at the same time as the rest of the program. thread::spawn starts one and returns a handle that you can use to wait for it.
move gives each thread its own copy of id. The threads may finish in any order, but join waits for each handle in the order they were created, so the output is always the same. join returns the value the closure produced.
मुख्य बातें
- spawn starts a thread and returns a handle.
- move gives the thread its own data.
- join waits and returns the thread's value.
चलने योग्य Rust उदाहरण
Rust
main.rs
use std::thread;
fn main() {
let mut handles = Vec::new();
for id in 1..=3u64 {
let handle = thread::spawn(move || {
let total: u64 = (1..=id * 1000).sum();
(id, total)
});
handles.push(handle);
}
for handle in handles {
let (id, total) = handle.join().unwrap();
println!("worker {id} summed to {total}");
}
}
worker 1 summed to 500500
worker 2 summed to 2001000
worker 3 summed to 4501500अभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज