title: How to deal with concurrency issues brought by NSStream run loop scheduling using GCD?
body: <p>I have the following situation where I create a GCD dispatch queue and in it I schedule an <code>NSStream</code> to the current <code>NSRunLoop</code>, as is required in its specification for it to emit delegate events, and then I make the run loop for that thread run using <code>[[NSRunLoop currentRunLoop run]</code>.</p>
  
  <p>This generates three possible scenarios:</p>
  
  <ol>
  <li><p>Create a serial queue in which an initial write message is sent through the stream and other write messages are only sent when there's a delegate callback from the <code>NSStream</code> object, as attempting to write new messages without respecting this pattern (this would be desirable) will fail as the queue is locked by the run loop running.</p></li>
  <li><p>Create a concurrent queue in which messages can be written to the stream freely, as blocks sent to the queue will be executed concurrently with the block that's running the run loop. However, while it is desirable to make writing messages and the run loop running concurrent, it certainly is not desirable to have to blocks in the queue running concurrently attempting to write at the same time to the stream.</p></li>
  <li><p>Create two queues -- one responsible for keeping the run loop alive and receive read-from-stream callbacks and another one for sending asynchronous write messages to the stream. This would seem ideal, however it seems that the <code>NSStream</code> documentation specifically states that one should not attempt to read/write to a stream outside the thread it is scheduled in.</p></li>
  </ol>
  
  <p>Given these scenarios none of which are ideal, how to solve these problems?</p>