Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does dispatch_set_target_queue work?

Due to the lack of material on dispatch_set_target_queue, I have come here for help, so thanks!

Here is my test code:

dispatch_queue_t mySerialDispatchQueue1 = dispatch_queue_create("come.itenyh", NULL);
dispatch_queue_t mySerialDispatchQueue2 = dispatch_queue_create("come.itenyh1", NULL);

dispatch_set_target_queue(mySerialDispatchQueue1, mySerialDispatchQueue2);

dispatch_async(mySerialDispatchQueue1, ^{[self task:@"s1"];});

dispatch_async(mySerialDispatchQueue2, ^{[self task:@"p1"];});

dispatch_async(mySerialDispatchQueue1, ^{[self task:@"s2"];});

- (void)task:(NSString *)taskid
{

        NSLog(@"Now executing taskid:%@", taskid);

        [NSThread sleepForTimeInterval:5];

}

Now if I set

 dispatch_set_target_queue(mySerialDispatchQueue2, mySerialDispatchQueue1);

then the result is:

2014-04-16 22:23:49.581 ITGCDLearning[66758:1303] Now executing taskid:s1
2014-04-16 22:23:54.585 ITGCDLearning[66758:1303] Now executing taskid:s2
2014-04-16 22:23:59.586 ITGCDLearning[66758:1303] Now executing taskid:p1

and on the contrary, If I set

dispatch_set_target_queue(mySerialDispatchQueue1, mySerialDispatchQueue2);

then the result is:

2014-04-16 22:28:37.910 ITGCDLearning[66795:1303] Now executing taskid:s1
2014-04-16 22:28:42.913 ITGCDLearning[66795:1303] Now executing taskid:p1
2014-04-16 22:28:47.915 ITGCDLearning[66795:1303] Now executing taskid:s2

I know that the dispatch_set_target_queue function can

  • change the priorty of the queue
  • create a hierarchy of dispatch queues.

I think it is the second point that leads to the result in my code, but don't really know the specific details. Can someone explain it to me?

like image 493
itenyh Avatar asked Apr 16 '14 14:04

itenyh


1 Answers

According to me when you set a target queue to other you are synchronizing the task of both the queue so
In first case:

dispatch_set_target_queue(mySerialDispatchQueue2, mySerialDispatchQueue1);

mySerialDispatchQueue1 is target queue so all the task added in mySerialDispatchQueue2 is also enqueued from the mySerialDispatchQueue1. As it is target queue.So mySerialDispatchQueue1 has already two task so other one from queue mySerialDispatchQueue2 is added later.

In second Case:

dispatch_set_target_queue(mySerialDispatchQueue1, mySerialDispatchQueue2);

your target queue is mySerialDispatchQueue2 so in start when there is no task then task from mySerialDispatchQueue1 is added in the mySerialDispatchQueue2 then its own task is in queue. So in this way task has been added.

like image 106
Saurav Nagpal Avatar answered Sep 20 '22 00:09

Saurav Nagpal