How to make your
Ruby code faster
with Multithreading
Sun-Li Beatteay
About Me
● Software Engineer @
DigitalOcean
● Technical Writer:
@SunnyB on Medium
● GitHub: sunny-b
● Twitter: @SunnyPaxos
Key Takeaways
1. Processes vs. Threads
2. Concurrency vs. Parallelism
3. How to use multithreading to speed up your code
a. Race Conditions
b. Mutex
Processes vs. Threads
Processes
● Each process is a running program (web
browser, Slack, Ruby/Bash script, etc.)
● Each CPU can run one process at a time
○ A CPU core can have more than one
process, but it will context switch
between them.
● `top`
Threads
● Each process has one Main
thread
● Share memory (same heap)
● Separate call stacks
Why is multithreading useful?
Concurrency vs. Parallelism
Parallelism
Tasks are completed in
parallel without pausing
or switching.
Concurrency
● Tasks overlap, but
don’t necessarily run
in parallel.
● Concurrency is not
the same as
parallelism.
Concurrency in Ruby
● Standard version of Ruby (MRI)
can’t achieve parallelism when
multithreading.
● Global Interpreter Lock prevents
threads from executing in
parallel.
“Not real threads”
Examples
Threads are Asynchronous
Race Conditions
Mutex
● Prevents multiple threads from accessing the
same shared resource at the same time
● Ensures thread safety
Thank You!
● Medium: @SunnyB
● GitHub: sunny-b
● Twitter: @SunnyPaxos
● Email: sjbeatteay@gmail.com
● Personal: http://www.sunli.co

How to make your ruby code faster with multithreading