Welcome to our deep dive into Send and Sync Traits in Rust! These traits are crucial for understanding concurrent programming in Rust, and we'll cover them from the ground up, making sure to explain the why as well as the how.
Let's get started!
In Rust, Traits are similar to interfaces in other languages. They define a set of methods that a type can implement, providing a contract of sorts for the behavior of that type.
Send (Send) and Sync (Sync) are two traits in Rust that help manage concurrent execution.
Send) Trait šA type is Send if it can be safely sent between threads. This means that if a value of the type is moved or copied into a thread, it won't cause data races or other thread safety issues.
use std::marker::Send;
struct MyStruct;
impl Send for MyStruct {} // Explicitly marking MyStruct as Sendš” Pro Tip: If Rust can infer that a type is Send, you don't need to explicitly mark it.
Sync) Trait šA type is Sync if it can be safely shared between threads. This means that if multiple threads have a reference to a value of the type, they won't cause data races or other thread safety issues.
use std::marker::Sync;
struct MyStruct;
impl Sync for MyStruct {} // Explicitly marking MyStruct as Syncš” Pro Tip: If a type is already Send, it's also Sync.
Let's see these traits in action with a practical example.
use std::thread;
use std::sync::Arc;
use std::marker::Send;
struct MyStruct {
data: i32,
}
impl Send for MyStruct {}
impl MyStruct {
fn new(data: i32) -> Arc<MyStruct> {
Arc::new(MyStruct { data })
}
fn get_data(&self) -> i32 {
self.data
}
fn set_data(&mut self, data: i32) {
self.data = data;
}
}
fn main() {
let my_struct = MyStruct::new(42);
let thread1 = thread::spawn(move || {
my_struct.set_data(100);
});
let thread2 = thread::spawn(move || {
assert_eq!(my_struct.get_data(), 100);
});
thread1.join().unwrap();
thread2.join().unwrap();
}In this example, we have a MyStruct type that is Send and Sync. We create a new MyStruct instance, and then spawn two threads to manipulate and access the data. The Arc type (Atomic Reference Count) is used to allow multiple threads to share the same MyStruct instance while maintaining thread safety.
What does the Send trait indicate about a type in Rust?
Which of the following types in the example is `Sync`?
That's it for our Send and Sync Traits lesson! By now, you should have a good understanding of these important Rust concepts. Happy coding! š»