Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top