Things learn from "Working with Ruby threads"

23 Apr 2020

Concurrency VS. Parallelism

  • Concurrency is about dealing with lots of things at once
  • Parallelism is about doing lots of things at once

Not the same, but related. One is about structure, one is about execution.

Ruby’s thread is hand over to System thread manager

Ruby’s thread is hand over to system thread manager. Two thread may work in same CPU or in diferent CPU core. So concurrency only provides a way to structure a solution to solve a problem that may (but not necessarily) be parallelizable.

So the tasks handle by threads aren’t being accomplished any quicker; they’re just being organized differenctly.

Ruby GIL

GIL - Global Interpreter Lock

If one of threads want to execute some Ruby code, it will have to acquire the lock. One, and only one, thread can hold the lock at any give time. While one thread holds the lock, other threads need to wait for their turn to acquire the lock. This has some very important implications for MRI. The biggest implication is that Ruby code will never run in parallel on MRI. The GIL prevents it.

Threads count better to be less of same with the CPU core

If the threads count is greater than CPU core. The CPU usage will be consume by context switch.

The specific number may need to measure. Keep measure.

The safest path to concurrency

  1. Don’t do it.
  2. If you must do it, don’t share data across threads.
  3. If you must share data across threads, don’t share mutable data.
  4. If you must share mutable data across threads, synchronize access to the data.

Ruby thread safe way

  • Use mutex
  • Use thread safe data structures
    • Queue
    • thread_safe gem
    • Immutable data
  • Thread-locals
  • Actor Model
  • JRuby, Rubinis
  • Concurrenmcy Ruby
Back to top