Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ruby Memory Model

Ruby Memory Model

Garden City Ruby Conference - Ruby Memory Model
What is a Memory Model?
Is Ruby really Threadsafe because it is single threaded?
How is single threading implemented in MRI?
Threadsafety in Rubinius and JRuby without GIL.

Video: http://www.confreaks.com/videos/2922-gardencityruby-ruby-memory-model

HariKrishnan

January 04, 2014
Tweet

More Decks by HariKrishnan

Other Decks in Programming

Transcript

  1. Increment operation is not a single instruction • Retrieve the

    current value of @count. • Increment the retrieved value by 1. • Store the incremented value back in @count.
  2. Thread A Thread B @count = 0 Load @count =

    0 Increment Store Load Increment Store @count = 1 @count = 2 @count = 1
  3. Thread A Thread B @count = 0 Load @count =

    0 Increment Store Load Increment Store @count = 1
  4. What is a memory model? A memory model describes the

    interactions of threads through memory and their shared use of the data
  5. Concurrency is about Interleavings Thread A - Load Thread A

    - Increment Thread B - Load Thread A - Store Thread B - Increment Thread B - Store
  6. How is Ruby made Single Threaded • 1.8 - Green

    Threads - Global Interpreter Lock • 1.9 - OS Threads - Global VM Lock
  7. How does GIL work? Ruby Thread 1 Ruby Thread 2

    OS Thread 1 OS 2 Timer Thread Wake up! Interrupt
  8. GIL Details • GIL is acquired at start of Thread

    block and released once done • To ensure fairness a timer thread sends an interrupt to the Thread holding GIL when other threads are waiting • The Thread holding GIL may choose to release it based on many parameters Refer to this excellent blog post by Jesse Storimer - http://www.jstorimer.com/blogs/workingwithcode/8085491- nobody-understands-the-gil
  9. Never depend on GIL for Thread Safety • GIL does

    not have a specification • It also ties us to MRI • Rubinius and JRuby do not have GIL
  10. Ruby right now depends on underlying Virtual Machines • MRI

    is not much of an interpreter. It is a VM. - No specification for Memory Model • JRuby - JVM - JSR 133 • Rubinius - LLVM for JIT -
  11. Gems to the rescue • atomic - https://github.com/headius/ruby- atomic •

    thread_safe - https://github. com/headius/thread_safe