3

I created this thread in my iOS app, and I'd like to stop it:

dispatch_queue_t myDispatch = dispatch_queue_create("com.myqueue", DISPATCH_QUEUE_CONCURRENT);

myDispatch thread within it invokes dispatch_global_queue and dispatch_main_queue respectively to execute heavy operations and to execute graphics operations. But in response to a user action in the app can be called another function that uses another queue very similar to myDispatch. If myDispatch thread is terminated, there are no problems, but this call can also occur during the execution of myDispatch thread, and so my app crashes because both thread use the same arrays. There is a way to stop or kill a thread before its termination? I'd like to kill the thread currently running and start the new thread.

Pinturikkio
  • 1,490
  • 1
  • 14
  • 28
  • 1
    See http://stackoverflow.com/questions/5449469/can-you-use-cancel-iscancelled-with-gcd-dispatch-async. It covers this more broadly. – Rob Napier May 28 '14 at 14:20
  • 1
    While you can write your own cancellation code for GCD, most of us would gravitate to `NSOperationQueue` and cancelable `NSOperation` subclass. See [Responding to Cancellation Events](https://developer.apple.com/library/mac/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationObjects/OperationObjects.html#//apple_ref/doc/uid/TP40008091-CH101-SW24) in the _Operation Queues_ chapter of the _Concurrency Programming Guide._ – Rob May 28 '14 at 15:12
  • I'd actually step back, though, and ask whether a cancelable operation on a concurrent queue was the right architecture, anyway. If you're trying to coordinate interaction with a mutable array (which by itself is not thread-safe), you'd often use a serial queue for that. It depends upon what you're trying to do, and I'm not sure if we have enough here to provide the right broader architectural counsel. – Rob May 28 '14 at 15:22

2 Answers2

4

If you want to cancel/stop background work you should be using NSOperation since as far as I know once you dispatch a block with GCD you lose control of it.

lucianomarisi
  • 1,552
  • 11
  • 24
  • 2
    it is the same -- in both cases the function isn't stopped but you have to check for isCancelled yourself. NSOperation just provides convenience -- you can easily do that with a block. -- Anyway this is ok advice as you should you use the NSOperation convenience here – Daij-Djan May 28 '14 at 14:26
0

To cancel a GCD thread you have to use your own atomic flag.

Ganesh Bavaskar
  • 754
  • 6
  • 15