title: Downloading Images in order of url's - iOS Swift
body: <p>I have 10 urls in an array and when 4 of them downloaded I need to display them. Im using Semaphores and groups to implement . But looks like im hitting deadlock. Not sure how to proceed. Please advice how I can</p>
  <p>Simulating same in playground:</p>
  <pre class="lang-swift prettyprint-override"><code>PlaygroundPage.current.needsIndefiniteExecution = true
  
  let group = DispatchGroup()
  let queue = DispatchQueue.global(qos: .userInteractive)
  let semaphore = DispatchSemaphore(value: 4)
  var nums: [Int] = []
  for i in 1...10 {
      
      group.enter()
      semaphore.wait()
      queue.async(group: group) {
          print(&quot;Downloading image \(i)&quot;)
          // Simulate a network wait
          Thread.sleep(forTimeInterval: 3)
          nums.append(i)
          print(&quot;Hola image \(i)&quot;)
          if nums.count == 4 {
              print(&quot;4 downloaded&quot;)
              semaphore.signal()
              group.leave()
          }
      }
      if nums.count == 4 {
          break
      }
  }
  
  group.notify(queue: DispatchQueue.main) {
      print(nums)
  }
  </code></pre>
  <p>I get this in o/p console</p>
  <pre><code>&gt; Downloading image 1
  &gt; Downloading image 2
  &gt; Downloading image 3
  &gt; Downloading image 4
  </code></pre>
  <blockquote>
  <p>Semaphores(41269,0x70000ade5000) malloc: *** error for object 0x1077d4750: pointer being freed was not allocated</p>
  <p>Semaphores(41269,0x70000ade5000) malloc: *** set a breakpoint in malloc_error_break to debug</p>
  </blockquote>
  <p>I'm expecting to print [1,2,3,4] in order</p>
  <p>I know im trying to access a shared resource in async but not sure how I can fix this. Please advice</p>
  <p>Also How can I use this with semaphore's if I want to download 4,4,2 tasks at a time so it display [1,2,3,4,5,6,7,8,9,10] in my ouput</p>