Skip to Content
Rust Atomics and Locks
book

Rust Atomics and Locks

by Mara Bos
January 2023
Intermediate to advanced
249 pages
6h 11m
English
O'Reilly Media, Inc.
Book available
Content preview from Rust Atomics and Locks

Chapter 5. Building Our Own Channels

Channels can be used to send data between threads, and they come in many variants. Some channels can only be used between exactly one sender and one receiver, while others can send from any number of threads, or even allow multiple receivers. Some channels are blocking, meaning that receiving (and sometimes sending) is a blocking operation, making your thread sleep until the operation can be completed. Some channels are optimized for throughput, while others are optimized for low latency.

The variations are endless, and there is no one-size-fits-all version that fits all use cases.

In this chapter, we’ll implement a few relatively simple channels to not only explore some more applications of atomics, but also to learn more about how our requirements and assumptions can be captured in Rust’s type system.

A Simple Mutex-Based Channel

A basic channel implementation does not require any knowledge of atomics. We can take a VecDeque, which is basically a Vec that allows for efficient adding and removing of elements on both ends, and protect it with a Mutex to allow multiple threads to access it. We then use the VecDeque as a queue of data, often called messages, that’s been sent but not yet received. Any thread that wants to send a message can simply add it to the back of the queue, and any thread that wants to receive a message just has to remove one from the front of the queue.

There’s just one more thing to add, which is used to make the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Command-Line Rust

Command-Line Rust

Ken Youens-Clark
Rust in Action

Rust in Action

Tim McNamara
Programming Rust, 2nd Edition

Programming Rust, 2nd Edition

Jim Blandy, Jason Orendorff, Leonora F. S. Tindall

Publisher Resources

ISBN: 9781098119430Errata PageSupplemental Content