2

I have this simple code to perform a network request:

class Downloader {
  var isCompleted = false
  func start() {
    URLSession.shared.dataTask(with: url) { data, response, error in
      isCompleted = true
    }
  }
}

I want to check isCompleted in other code to determine if the request is completed or not.

The problem is that I seem to have created data race this way, because the flag is set in a background queue, and it might be checked in any queue.

Is there any way to make isCompleted thread safe using GCD?

hgl
  • 2,034
  • 4
  • 21
  • 30
  • You need to provide more information on what you want to do when the download is complete. There are a number of techniques that could work for you; you could pass a completion handler to the download function, you could use a delegation pattern, you could use a `DispatchGroup` or post a `Notification` – Paulw11 Nov 03 '17 at 08:39
  • If you want "thread safe" for a variable, this thread may help https://stackoverflow.com/questions/30851339/how-do-i-atomically-increment-a-variable-in-swift – t4nhpt Nov 03 '17 at 09:06

0 Answers0