Using a single shared background thread for iOS data processing?

后端 未结 3 894
南旧
南旧 2021-02-10 06:38

I have an app where I\'m downloading a number of resources from the network, and doing some processing on each one. I don\'t want this work happening on the main thread, but it\

3条回答
  •  清酒与你
    2021-02-10 07:19

    Surprisingly, though, there doesn't seem to be a simple way to get all of this work happening on a single, shared thread, rather than spawning a new thread for each task.

    This is exactly what GCD is for. GCD maintains a pool of threads that can be used for executing arbitrary blocks of code, and it takes care of managing that pool for best results on whatever hardware is at hand. This avoids the cost of constantly creating and destroying threads and also saves you from having to figure out how many processors are available, etc.

    Tommy provides the right answer if you really care that only a single thread should be used, but it sounds like you're really just trying to avoid creating one thread per task.

    This is complicated by the large number of paths to achieving concurrency that seem to have cropped up over the years. (Explicit NSThreads, NSOperationQueue, GCD, etc.)

    NSOperationQueue uses GCD, so you can use that if it makes life easier than using GCD directly.

    Use GCD, and assume that it's smarter than I about thread (re)use?

    Exactly.

提交回复
热议问题