1

If I store a dispatch_queue_t like so:

@property(assign, nonatomic) dispatch_queue_t myQueue;

...

_myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

Later, when I do operations like

dispatch_async(_myQueue, ^{
  NSLog(@"Hi!");
});

and then somewhere else

dispatch_async(_myQueue, ^{
  NSLog(@"Hello!");
});

are these blocks executed on the same thread? If not, how do I ensure that they are? Basically I want to keep a reference to a thread and make it execute some actions only on that thread.

Nick C
  • 514
  • 3
  • 12

1 Answers1

5

How threads are assigned to queues is an implementation detail of Grand Central Dispatch. Two blocks dispatched to a (serial or concurrent) queue are not necessarily executed on the same thread. The only exception is the "main queue" which only executes on the main thread.

If you really have the requirement that the code executes on the same thread, you have to use a different threading method, e.g. NSThread or pthread_create.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Where should I look, documentation-wise, for learning about this and the differences between serial and concurrent threads? I've only had exposure to the simplest GCD methods and threading in C. – Nick C Sep 01 '13 at 19:37
  • @NickC: ["Concurrency Programming Guide"](https://developer.apple.com/library/ios/DOCUMENTATION/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html), ["Threading Programming Guide"](https://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/Multithreading/Introduction/Introduction.html#//apple_ref/doc/uid/10000057i). – Martin R Sep 01 '13 at 19:39
  • One last thing -- say I send a block to a dispatch_async on a global_queue -- is the entire method executed on the same thread? – Nick C Sep 01 '13 at 20:26