Posts

Showing posts with the label multithreading

Understanding the Sync Trait in Rust

Image
When writing concurrent code in Rust, one of the most important concepts to grasp is the Sync trait. Rust uses Sync and Send to define how data can safely move or be shared between threads. These traits are not just ordinary traits you implement manually; they are built into the language as special “marker traits” that the compiler uses to enforce thread safety rules at compile time. Understanding Sync helps you design safe concurrent programs without data races or undefined behavior.   A type is Sync if it can be safely referenced from multiple threads at the same time. In other words, if &T is Send , then T is Sync . This means that if you have a reference to a value, you can share that reference across threads without breaking memory safety. Many types in Rust are automatically Sync because they use internal synchronization or are immutable by nature. For example, primitive types like i32, bool, and f64 are Sync, as are most collections when they contain Sync types. ...