SlideShare a Scribd company logo
1 of 51
Aaron Turon	

Mozilla Research
InfoQ.com: News & Community Site
• 750,000 unique visitors/month
• Published in 4 languages (English, Chinese, Japanese and Brazilian
Portuguese)
• Post content from our QCon conferences
• News 15-20 / week
• Articles 3-4 / week
• Presentations (videos) 12-15 / week
• Interviews 2-3 / week
• Books 1 / month
Watch the video with slide
synchronization on InfoQ.com!
http://www.infoq.com/presentations
/rust-thread-safety
Purpose of QCon
- to empower software development by facilitating the spread of
knowledge and innovation
Strategy
- practitioner-driven conference designed for YOU: influencers of
change and innovation in your teams
- speakers and topics driving the evolution and innovation
- connecting and catalyzing the influencers and innovators
Highlights
- attended by more than 12,000 delegates since 2007
- held in 9 cities worldwide
Presented at QCon San Francisco
www.qconsf.com
Rust is a systems programming language
that runs blazingly fast, prevents nearly all
segfaults, and guarantees thread safety. 	

- https://www.rust-lang.org/
Safety
Control
C C++
Go
Java
Haskell
Scala
“Low-level”
Conventional wisdom
The Essence of Rust
Low-level == Unsafe
+ Safe
Why Rust?
- You’re already doing systems programming, 

want safety or expressiveness.	

!
- You wish you could do some systems work	

- Maybe as an embedded piece in your

Java, Python, JS, Ruby, …
Why Mozilla?
Browsers need control.
Browsers need safety.
Servo: Next-generation
browser built in Rust.
Rust: New language for 	

safe systems programming.
What is control?
void example() {
vector<string> vector;
…
auto& elem = vector[0];
…
}
string[0]
…elem
vector
data
length
capacity
[0]
[n]
[…]
…
‘H’
…
‘e’
Stack and inline layout.
Interior references
Deterministic destruction
Stack Heap
C++
Zero-cost abstraction
Ability to define abstractions that	

optimize away to nothing.
vector data
length
cap.
[0]
[…]
data cap.
‘H’
‘e’
[…]
Not just memory layout:	

- Static dispatch	

- Template expansion	

- … Java
What is safety?
void example() {
vector<string> vector;
…
auto& elem = vector[0];
vector.push_back(some_string);
cout << elem;
}
vector
data
length
capacity
[0]
…
[0]
[1]
elem
Aliasing: more than	

one pointer to same	

memory.
Dangling pointer: pointer	

to freed memory.
C++
Mutating the vector	

freed old contents.
What about GC?
No control.
Requires a runtime.
Insufficient to prevent related problems:	

iterator invalidation, data races, many others.
Ownership & Borrowing
Memory	

safety
Data-race	

freedom	

(and more)
No need for	

a runtime
GCC++
… Plus lots of goodies
- Pattern matching	

- Traits	

- “Smart” pointers	

- Metaprogramming	

- Package management (think Bundler)
TL;DR: Rust is a modern language
Ownership
!
n. The act, state, or right of possessing something.
Ownership (T)
Aliasing Mutation
vec
data
length
capacity
vec
data
length
capacity
1
2
fn give() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
take(vec);
…
}
fn take(vec: Vec<int>) {
// …
}
!
!
!
Take ownership	

of aVec<int>
fn give() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
take(vec);
…
}
vec.push(2);
Compiler enforces moves
fn take(vec: Vec<int>) {
// …
}
!
!
!Error: vec has been moved
Prevents:	

- use after free	

- double moves	

- …
Borrow
!
v. To receive something with the promise of returning it.
Shared borrow (&T)
Aliasing Mutation
Mutable borrow (&mut T)
Aliasing Mutation
fn lender() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
use(&vec);
…
}
fn use(vec: &Vec<int>) {
// …
}
!
!
!
1
2vec
data
length
capacity
vec
“Shared reference	

toVec<int>”
Loan out vec
fn use(vec: &Vec<int>) {
vec.push(3);
vec[1] += 2;
}
Shared references are immutable:
Error: cannot mutate shared reference
* Actually: mutation only in controlled circumstances
*
Aliasing Mutation
fn push_all(from: &Vec<int>, to: &mut Vec<int>) {
for elem in from {
to.push(*elem);
}
}
Mutable references
mutable reference to Vec<int>
push() is legal
1
2
3
from
to
elem
1
…
fn push_all(from: &Vec<int>, to: &mut Vec<int>) {
for elem in from {
to.push(*elem);
}
}
Mutable references
What if from and to are equal?
1
2
3
from
to
elem
1
2
3
…
1
fn push_all(from: &Vec<int>, to: &mut Vec<int>) {
for elem in from {
to.push(*elem);
}
} dangling pointer
fn push_all(from: &Vec<int>, to: &mut Vec<int>) {…}
!
fn caller() {
let mut vec = …;
push_all(&vec, &mut vec);
}
shared reference
Error: cannot have both shared and
mutable reference at same time
A &mut T is the only way to access	

the memory it points at
{
let mut vec = Vec::new();
…
for i in 0 .. vec.len() {
let elem: &int = &vec[i];
…
vec.push(…);
}
…
vec.push(…);
}
Borrows restrict access to
the original path for their
duration.
Error: vec[i] is borrowed,
cannot mutate
OK. loan expired.
&
&mut
no writes, no moves
no access at all
Concurrency
!
n. several computations executing simultaneously, and
potentially interacting with each other.
Rust’s vision for concurrency
Originally:	

!
Now:
only isolated message passing
libraries for many paradigms,	

using ownership to avoid footguns,	

guaranteeing no data races
Data race
Two unsynchronized threads	

accessing same data
where at least one writes.
✎
✎
Aliasing
Mutation
No ordering
Data race
Sound familiar?
No data races =	

No accidentally-shared state.	

!
All sharing is explicit!
*some_value = 5;
return *some_value == 5; // ALWAYS true
Messaging
(ownership)
data
length
capacity
data
length
capacity
move || {
let m = Vec::new();
…
tx.send(m);
}
rx
tx
tx
m
fn parent() {
let (tx, rx) = channel();
spawn(move || {…});
let m = rx.recv();
}
Locked mutable access
(ownership, borrowing)
✎
✎
fn sync_inc(mutex: &Mutex<int>) {
let mut data = mutex.lock();
*data += 1;
}
Destructor releases lock
Yields a mutable reference to data
Destructor runs here, releasing lock
Disjoint, scoped access
(borrowing)
✎
✎
fn qsort(vec: &mut [int]) {
if vec.len() <= 1 { return; }
let pivot = vec[random(vec.len())];
let mid = vec.partition(vec, pivot);
let (less, greater) = vec.split_at_mut(mid);
qsort(less);
qsort(greater);
}
[0] [1] [2] [3] […] [n]
let vec: &mut [int] = …;
less greater
fn split_at_mut(&mut self, mid: usize)
-> (&mut [T], & mut [T])
[0] [1] [2] [3] […] [n]
let vec: &mut [int] = …;
less greater
fn parallel_qsort(vec: &mut [int]) {
if vec.len() <= 1 { return; }
let pivot = vec[random(vec.len())];
let mid = vec.partition(vec, pivot);
let (less, greater) = vec.split_at_mut(mid);
parallel::join(
|| parallel_qsort(less),
|| parallel_qsort(greater)
);
}
Arc<Vec<int>>: Send
Rc<Vec<int>> : !Send
fn send<T: Send>(&self, t: T)
Only “sendable” types
Static checking for thread safety
And beyond…
Concurrency is an area of active development.	

!
Either already have or have plans for:	

- Atomic primitives	

- Non-blocking queues	

- Concurrent hashtables	

- Lightweight thread pools	

- Futures	

- CILK-style fork-join concurrency	

- etc.
Always data-race free
Unsafe
!
adj. not safe; hazardous
Safe abstractions
unsafe {
…
}
Useful for:	

	

 Bending mutation/aliasing rules (split_at_mut)	

	

 Interfacing with C code
Trust me.
fn something_safe(…) {
!
!
!
!
}
Validates input, etc.
Ownership enables safe abstraction boundaries.
Community
!
n. A feeling of fellowship with others sharing similar goals.
“The Rust community seems to be
populated entirely by human beings.
I have no idea how this was done.”	

— Jamie Brandon
It takes a village…
Community focus from the start:	

	

 Rust 1.0 had > 1,000 contributors	

	

 Welcoming, pragmatic culture	

!
Developed “in the open”	

	

 Much iteration;	

humility is key!	

!
Clear leadership	

	

 Mix of academic and engineering backgrounds	

	

 “Keepers of the vision”
Memory safety	

Concurrency	

Abstraction	

Stability
without
garbage collection	

data races	

overhead	

stagnation
Hack without fear!
Articulating the vision
Watch the video with slide synchronization on
InfoQ.com!
http://www.infoq.com/presentations/rust-
thread-safety

More Related Content

What's hot

What's hot (20)

Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Why rust?
Why rust?Why rust?
Why rust?
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
 
Rust Primer
Rust PrimerRust Primer
Rust Primer
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming Language
 
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
 
Embedded Rust on IoT devices
Embedded Rust on IoT devicesEmbedded Rust on IoT devices
Embedded Rust on IoT devices
 
Is Rust Programming ready for embedded development?
Is Rust Programming ready for embedded development?Is Rust Programming ready for embedded development?
Is Rust Programming ready for embedded development?
 
Rust
RustRust
Rust
 
Introduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractionsIntroduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractions
 
Deep C
Deep CDeep C
Deep C
 
The Rust Programming Language
The Rust Programming LanguageThe Rust Programming Language
The Rust Programming Language
 
Rust
RustRust
Rust
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practice
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
[KubeConUS2019 Docker, Inc. Booth] Distributed Builds on Kubernetes with Bui...
 [KubeConUS2019 Docker, Inc. Booth] Distributed Builds on Kubernetes with Bui... [KubeConUS2019 Docker, Inc. Booth] Distributed Builds on Kubernetes with Bui...
[KubeConUS2019 Docker, Inc. Booth] Distributed Builds on Kubernetes with Bui...
 
Working Remotely (via SSH) Rocks!
Working Remotely (via SSH) Rocks!Working Remotely (via SSH) Rocks!
Working Remotely (via SSH) Rocks!
 
What Can Compilers Do for Us?
What Can Compilers Do for Us?What Can Compilers Do for Us?
What Can Compilers Do for Us?
 

Viewers also liked

Lessons in failure entrepreneurship is a journey through zeroes
Lessons in failure   entrepreneurship is a journey through zeroesLessons in failure   entrepreneurship is a journey through zeroes
Lessons in failure entrepreneurship is a journey through zeroes
Kevin Li
 
Final ppt of financial mgmt
Final ppt of financial mgmtFinal ppt of financial mgmt
Final ppt of financial mgmt
Payal Tharani
 
Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled Presentation
James Stearns
 
Technology’s role in 21st century learning
Technology’s role in 21st century learningTechnology’s role in 21st century learning
Technology’s role in 21st century learning
f3tm3
 

Viewers also liked (20)

Rust is for Robots!
Rust is for Robots!Rust is for Robots!
Rust is for Robots!
 
Servo: The parallel web engine
Servo: The parallel web engineServo: The parallel web engine
Servo: The parallel web engine
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
 
Type-Directed TDD in Rust: a case study using FizzBuzz
Type-Directed TDD in Rust: a case study using FizzBuzzType-Directed TDD in Rust: a case study using FizzBuzz
Type-Directed TDD in Rust: a case study using FizzBuzz
 
What the &~#@&lt;!? (Memory Management in Rust)
What the &~#@&lt;!? (Memory Management in Rust)What the &~#@&lt;!? (Memory Management in Rust)
What the &~#@&lt;!? (Memory Management in Rust)
 
OOP in Rust
OOP in RustOOP in Rust
OOP in Rust
 
Machine Learning in Rust with Leaf and Collenchyma
Machine Learning in Rust with Leaf and CollenchymaMachine Learning in Rust with Leaf and Collenchyma
Machine Learning in Rust with Leaf and Collenchyma
 
Kernel-Level Programming: Entering Ring Naught
Kernel-Level Programming: Entering Ring NaughtKernel-Level Programming: Entering Ring Naught
Kernel-Level Programming: Entering Ring Naught
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
Ruby is Awesome and Rust is Awesome and Building a Game in Both is AWESOME
Ruby is Awesome and Rust is Awesome and Building a Game in Both is AWESOMERuby is Awesome and Rust is Awesome and Building a Game in Both is AWESOME
Ruby is Awesome and Rust is Awesome and Building a Game in Both is AWESOME
 
RUSTing -- Partially Ordered Rust Programming Ruminations
RUSTing -- Partially Ordered Rust Programming RuminationsRUSTing -- Partially Ordered Rust Programming Ruminations
RUSTing -- Partially Ordered Rust Programming Ruminations
 
Lessons in failure entrepreneurship is a journey through zeroes
Lessons in failure   entrepreneurship is a journey through zeroesLessons in failure   entrepreneurship is a journey through zeroes
Lessons in failure entrepreneurship is a journey through zeroes
 
Area de tecnologia e imformatica en el instituto
Area de tecnologia e imformatica en el institutoArea de tecnologia e imformatica en el instituto
Area de tecnologia e imformatica en el instituto
 
Final ppt of financial mgmt
Final ppt of financial mgmtFinal ppt of financial mgmt
Final ppt of financial mgmt
 
Magazine Questionnaire
Magazine QuestionnaireMagazine Questionnaire
Magazine Questionnaire
 
Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled Presentation
 
Презентация ПромРезерв (Москва)
Презентация ПромРезерв (Москва)Презентация ПромРезерв (Москва)
Презентация ПромРезерв (Москва)
 
CRNM - Health Study
CRNM - Health StudyCRNM - Health Study
CRNM - Health Study
 
Technology’s role in 21st century learning
Technology’s role in 21st century learningTechnology’s role in 21st century learning
Technology’s role in 21st century learning
 
Volunteer Editor Introduction
Volunteer Editor IntroductionVolunteer Editor Introduction
Volunteer Editor Introduction
 

Similar to Rust: Unlocking Systems Programming

The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
Baidu, Inc.
 

Similar to Rust: Unlocking Systems Programming (20)

Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup
 
Rust "Hot or Not" at Sioux
Rust "Hot or Not" at SiouxRust "Hot or Not" at Sioux
Rust "Hot or Not" at Sioux
 
C++ references
C++ referencesC++ references
C++ references
 
Rust: Reach Further
Rust: Reach FurtherRust: Reach Further
Rust: Reach Further
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Get Ahead with HTML5 on Moible
Get Ahead with HTML5 on MoibleGet Ahead with HTML5 on Moible
Get Ahead with HTML5 on Moible
 
Security in the blockchain
Security in the blockchainSecurity in the blockchain
Security in the blockchain
 
5 x HTML5 worth using in APEX (5)
5 x HTML5 worth using in APEX (5)5 x HTML5 worth using in APEX (5)
5 x HTML5 worth using in APEX (5)
 
Qt for S60
Qt for S60Qt for S60
Qt for S60
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
 
Return of c++
Return of c++Return of c++
Return of c++
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
TinyOS 2.1 tutorial at IPSN 2009
TinyOS 2.1 tutorial at IPSN 2009TinyOS 2.1 tutorial at IPSN 2009
TinyOS 2.1 tutorial at IPSN 2009
 
Capacity Planning for Linux Systems
Capacity Planning for Linux SystemsCapacity Planning for Linux Systems
Capacity Planning for Linux Systems
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Solving New School with the Old School (Clojure)
Solving New School with the Old School (Clojure)Solving New School with the Old School (Clojure)
Solving New School with the Old School (Clojure)
 
Gateway and secure micro services
Gateway and secure micro servicesGateway and secure micro services
Gateway and secure micro services
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
 
iPhone development from a Java perspective (Jazoon '09)
iPhone development from a Java perspective (Jazoon '09)iPhone development from a Java perspective (Jazoon '09)
iPhone development from a Java perspective (Jazoon '09)
 

More from C4Media

More from C4Media (20)

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live Video
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy Mobile
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java Applications
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No Keeper
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like Owners
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate Guide
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CD
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine Learning
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at Speed
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep Systems
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.js
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly Compiler
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix Scale
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's Edge
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home Everywhere
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing For
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data Engineering
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Rust: Unlocking Systems Programming

  • 2. InfoQ.com: News & Community Site • 750,000 unique visitors/month • Published in 4 languages (English, Chinese, Japanese and Brazilian Portuguese) • Post content from our QCon conferences • News 15-20 / week • Articles 3-4 / week • Presentations (videos) 12-15 / week • Interviews 2-3 / week • Books 1 / month Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations /rust-thread-safety
  • 3. Purpose of QCon - to empower software development by facilitating the spread of knowledge and innovation Strategy - practitioner-driven conference designed for YOU: influencers of change and innovation in your teams - speakers and topics driving the evolution and innovation - connecting and catalyzing the influencers and innovators Highlights - attended by more than 12,000 delegates since 2007 - held in 9 cities worldwide Presented at QCon San Francisco www.qconsf.com
  • 4. Rust is a systems programming language that runs blazingly fast, prevents nearly all segfaults, and guarantees thread safety. - https://www.rust-lang.org/
  • 6. Conventional wisdom The Essence of Rust Low-level == Unsafe + Safe
  • 7. Why Rust? - You’re already doing systems programming, 
 want safety or expressiveness. ! - You wish you could do some systems work - Maybe as an embedded piece in your
 Java, Python, JS, Ruby, …
  • 8. Why Mozilla? Browsers need control. Browsers need safety. Servo: Next-generation browser built in Rust. Rust: New language for safe systems programming.
  • 9. What is control? void example() { vector<string> vector; … auto& elem = vector[0]; … } string[0] …elem vector data length capacity [0] [n] […] … ‘H’ … ‘e’ Stack and inline layout. Interior references Deterministic destruction Stack Heap C++
  • 10. Zero-cost abstraction Ability to define abstractions that optimize away to nothing. vector data length cap. [0] […] data cap. ‘H’ ‘e’ […] Not just memory layout: - Static dispatch - Template expansion - … Java
  • 11. What is safety? void example() { vector<string> vector; … auto& elem = vector[0]; vector.push_back(some_string); cout << elem; } vector data length capacity [0] … [0] [1] elem Aliasing: more than one pointer to same memory. Dangling pointer: pointer to freed memory. C++ Mutating the vector freed old contents.
  • 12. What about GC? No control. Requires a runtime. Insufficient to prevent related problems: iterator invalidation, data races, many others.
  • 14. … Plus lots of goodies - Pattern matching - Traits - “Smart” pointers - Metaprogramming - Package management (think Bundler) TL;DR: Rust is a modern language
  • 15. Ownership ! n. The act, state, or right of possessing something.
  • 17. vec data length capacity vec data length capacity 1 2 fn give() { let mut vec = Vec::new(); vec.push(1); vec.push(2); take(vec); … } fn take(vec: Vec<int>) { // … } ! ! ! Take ownership of aVec<int>
  • 18. fn give() { let mut vec = Vec::new(); vec.push(1); vec.push(2); take(vec); … } vec.push(2); Compiler enforces moves fn take(vec: Vec<int>) { // … } ! ! !Error: vec has been moved Prevents: - use after free - double moves - …
  • 19. Borrow ! v. To receive something with the promise of returning it.
  • 21. Mutable borrow (&mut T) Aliasing Mutation
  • 22. fn lender() { let mut vec = Vec::new(); vec.push(1); vec.push(2); use(&vec); … } fn use(vec: &Vec<int>) { // … } ! ! ! 1 2vec data length capacity vec “Shared reference toVec<int>” Loan out vec
  • 23. fn use(vec: &Vec<int>) { vec.push(3); vec[1] += 2; } Shared references are immutable: Error: cannot mutate shared reference * Actually: mutation only in controlled circumstances * Aliasing Mutation
  • 24. fn push_all(from: &Vec<int>, to: &mut Vec<int>) { for elem in from { to.push(*elem); } } Mutable references mutable reference to Vec<int> push() is legal
  • 25. 1 2 3 from to elem 1 … fn push_all(from: &Vec<int>, to: &mut Vec<int>) { for elem in from { to.push(*elem); } } Mutable references
  • 26. What if from and to are equal? 1 2 3 from to elem 1 2 3 … 1 fn push_all(from: &Vec<int>, to: &mut Vec<int>) { for elem in from { to.push(*elem); } } dangling pointer
  • 27. fn push_all(from: &Vec<int>, to: &mut Vec<int>) {…} ! fn caller() { let mut vec = …; push_all(&vec, &mut vec); } shared reference Error: cannot have both shared and mutable reference at same time A &mut T is the only way to access the memory it points at
  • 28. { let mut vec = Vec::new(); … for i in 0 .. vec.len() { let elem: &int = &vec[i]; … vec.push(…); } … vec.push(…); } Borrows restrict access to the original path for their duration. Error: vec[i] is borrowed, cannot mutate OK. loan expired. & &mut no writes, no moves no access at all
  • 29. Concurrency ! n. several computations executing simultaneously, and potentially interacting with each other.
  • 30. Rust’s vision for concurrency Originally: ! Now: only isolated message passing libraries for many paradigms, using ownership to avoid footguns, guaranteeing no data races
  • 31. Data race Two unsynchronized threads accessing same data where at least one writes. ✎ ✎
  • 33. No data races = No accidentally-shared state. ! All sharing is explicit! *some_value = 5; return *some_value == 5; // ALWAYS true
  • 35. data length capacity data length capacity move || { let m = Vec::new(); … tx.send(m); } rx tx tx m fn parent() { let (tx, rx) = channel(); spawn(move || {…}); let m = rx.recv(); }
  • 36. Locked mutable access (ownership, borrowing) ✎ ✎
  • 37. fn sync_inc(mutex: &Mutex<int>) { let mut data = mutex.lock(); *data += 1; } Destructor releases lock Yields a mutable reference to data Destructor runs here, releasing lock
  • 39. fn qsort(vec: &mut [int]) { if vec.len() <= 1 { return; } let pivot = vec[random(vec.len())]; let mid = vec.partition(vec, pivot); let (less, greater) = vec.split_at_mut(mid); qsort(less); qsort(greater); } [0] [1] [2] [3] […] [n] let vec: &mut [int] = …; less greater
  • 40. fn split_at_mut(&mut self, mid: usize) -> (&mut [T], & mut [T])
  • 41. [0] [1] [2] [3] […] [n] let vec: &mut [int] = …; less greater fn parallel_qsort(vec: &mut [int]) { if vec.len() <= 1 { return; } let pivot = vec[random(vec.len())]; let mid = vec.partition(vec, pivot); let (less, greater) = vec.split_at_mut(mid); parallel::join( || parallel_qsort(less), || parallel_qsort(greater) ); }
  • 42. Arc<Vec<int>>: Send Rc<Vec<int>> : !Send fn send<T: Send>(&self, t: T) Only “sendable” types Static checking for thread safety
  • 43. And beyond… Concurrency is an area of active development. ! Either already have or have plans for: - Atomic primitives - Non-blocking queues - Concurrent hashtables - Lightweight thread pools - Futures - CILK-style fork-join concurrency - etc. Always data-race free
  • 45. Safe abstractions unsafe { … } Useful for: Bending mutation/aliasing rules (split_at_mut) Interfacing with C code Trust me. fn something_safe(…) { ! ! ! ! } Validates input, etc. Ownership enables safe abstraction boundaries.
  • 46. Community ! n. A feeling of fellowship with others sharing similar goals.
  • 47. “The Rust community seems to be populated entirely by human beings. I have no idea how this was done.” — Jamie Brandon
  • 48. It takes a village… Community focus from the start: Rust 1.0 had > 1,000 contributors Welcoming, pragmatic culture ! Developed “in the open” Much iteration; humility is key! ! Clear leadership Mix of academic and engineering backgrounds “Keepers of the vision”
  • 49.
  • 50. Memory safety Concurrency Abstraction Stability without garbage collection data races overhead stagnation Hack without fear! Articulating the vision
  • 51. Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations/rust- thread-safety