title: Ruby thread safe thread creation
body: <p>I came across this bit of code today:</p>
  
  <pre class="lang-rb prettyprint-override"><code>@thread ||= Thread.new do
    # this thread should only spin up once
  end
  </code></pre>
  
  <p>It is being called by multiple threads. I was worried that if multiple threads are calling this code that you could have multiple threads created since <code>@thread</code> access is not synchronized. However, I was told that this could not happen because of the Global Interpreter Lock. I did a little bit of reading about threads in Ruby and it seems like individual threads that are running Ruby code can get preempted by other threads. If this is the case, couldn't you have an interleaving like this:</p>
  
  <pre><code>Thread A             Thread B
  ========             ========
  Read from @thread    .
  Thread.New           .
  [Thread A preempted] .
  .                    Read from @thread
  .                    Thread.New
  .                    Write to @thread
  Write to @thread
  </code></pre>
  
  <p>Additionally, since access to @thread is not synchronized are writes to <code>@thread</code> guaranteed to be visible to all other threads? The memory models of other languages I've used in the past do not guarantee visibility of writes to memory unless you synchronize access to that memory using atomics, mutexes, etc.</p>
  
  <p>I'm still learning Ruby and realize I have a long way to go to understanding concurrency in Ruby. Any help on this would be super appreciated!</p>