This book will help you get the story straight when it comes to multi-threaded programming in Ruby. Heard of things like Ruby’s GIL? Mutexes? Race conditions? Actors? This book is a gentle introduction to these topics for the complete concurrency beginner. After reading, you’ll have a firm grasp on why multi-threaded concurrency matters, how to use multiple threads safely, what issues to be aware of in your libraries or your Rails apps, and even see some walkthroughs of real-world multi-threaded code. Don’t get left behind—join the conversation and take advantage of your modern multicore hardware.
This book was written and produced entirely by the author. We are proud to be distributing it.
About this Book
- 177 pages
- Release: P1.0 (2013-09-16)
- ISBN: pending
Working with Ruby Threads starts with an introduction to how threading works at a high level, showing you what your Ruby programs look like with multiple threads at play. You’ll learn about things such as context switching and race conditions.
From there, you’ll get a safari tour of Ruby’s Thread API, followed by a deep dive into the infamous GIL: its effects, its implementation, and the reason it’s there. Next you’ll look at JRuby and Rubinius, how they don’t have a GIL, and how this affects multi-threaded code when run on those implementations.
The middle section of the book is all about thread safety: what it means, what it looks like, how to write thread-safe code, how to recognize thread-dangerous code, and what options Ruby provides for writing correct concurrent programs. You’ll then look at abstractions on top of threads (such as Actors), and wrap up by walking through some real-world, multi-threaded code. You’ll get to see a selection from the Puma web server, and one from the Celluloid-based Sidekiq project, bit by bit with explanations along the way. Two appendices take you into advanced topics such as immutability and compare-and-swap operations.
After all this, you’ll have a good handle on multi-threaded concurrency, and you won’t be afraid to apply it to your next Ruby project.
What You Need
You’ll need some experience with Ruby and a modern multi-core computer. The book uses and contrasts MRI 2.0.0, JRuby 1.7.4, and Rubinius 2.0.0-rc1.
Contents and Extracts
- You’re Always in a Thread
- Threads of Execution
- Lifecycle of a Thread
- Concurrent != Parallel
- The GIL and MRI
- Real Parallel Threading with JRuby and Rubinius
- How Many Threads Are Too Many?
- Thread safety
- Protecting Data with Mutexes
- Signaling Threads with Condition Variables
- Thread-safe Data Structures
- Writing Thread-safe Code
- Thread-safety on Rails
- Wrap Your Threads in an Abstraction
- How Sidekiq Uses Celluloid
- Puma’s Thread Pool Implementation
- Appendix: Atomic Compare-and-set Operations
- Appendix: Thread-safety and Immutability