title: What is the correct way to implement a process in Swift that continuously pulls from a potentially empty queue?
body: <p>I have a module that feeds and populates a queue with resources, specifically URL Strings. That module spins off asynchronous network requests which use an onSuccess callback that pushes to the URL_ResourceQueue inside of a serial queue specifically for accessing that resource. </p>
  
  <p>Now, I would like to have a different process dequeue from the URL String Queue constantly. If it pulls a URL, it should process a URL and then put it's data into another queue for use by the UI later on. If the queue is empty, it should start a timeout timer, which if it goes off will kill the dequeuing and go tell the UI what happened. </p>
  
  <p>A high level doodle of what I'm trying to acomplish here:</p>
  
  <p><a href="https://i.stack.imgur.com/rjsih.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rjsih.jpg" alt="A high level doodle of what I&#39;m trying to acomplish here."></a></p>
  
  <p>So far, I figured I could just do this with a loop (pseudocode):</p>
  
  <pre><code>while (running) {
      var url : String?
  
      inURLResourceGCD.sync { 
            var quit = doTimeoutStuff();
  
            if (quit) { running = false; return; }
            url = URLQueue.dequeue(); 
      }
  
      launchAsyncURLProcessing();
  }
  </code></pre>
  
  <p>But a loop seems to have all sorts of problems. It asks the queue if its empty so often that it can stall the serial GCD queue in other tasks. It also seems wasteful to be processing so many requests for when the queue is empty due to the URL Generator still running. </p>
  
  <p>What's the proper way of handling this?</p>