title: Why are these pthreads segmentation faults possible?
body: <p>In <a href="https://gist.github.com/krakjoe/6437782" rel="nofollow">this introduction to pthreads</a> I read that:</p>
  
  <blockquote>
    <p>When the programmer calls Thread::start, a new thread is created, a PHP interpreter context is initialized and then (safely) manipulated to mirror the context that made the call to ::start.</p>
  </blockquote>
  
  <p>And later in the text the <em>segmentation fault</em> problem is addressed. This example of a segmentation fault is given:</p>
  
  <pre><code>class W extends Worker {
      public function run(){}
  }
  class S extends Stackable {
      public function run(){}
  }
  /* 1 */
  $w = new W();
  /* 2 */
  $j = array(
      new S(), new S(), new S()
  );
  /* 3 */
  foreach ($j as $job)
      $w-&gt;stack($job);
  /* 4 */
  $j = array();
  $w-&gt;start();
  $w-&gt;shutdown();
  </code></pre>
  
  <blockquote>
    <p>The above example will always segfault; steps 1-3 are perfectly normal, but before the Worker is started the stacked objects are deleted, resulting in a segfault when the Worker is allowed to start. </p>
  </blockquote>
  
  <p><strong>The questions are:</strong></p>
  
  <ol>
  <li>Is the whole context that starts the new thread copied into the new thread when <code>start()</code> is called, or only at the time the interpreter sees a reference to a variable of the old context? In other words, is it enough to keep refcounts > 0 until <code>start()</code> is called?</li>
  <li>Shouldn't references to the <code>Stackable</code> array enties be stored inside the <code>Worker</code> object so that the refcount of them after overwriting <code>$j</code> is still 1 and no segfault could occur?</li>
  </ol>