How are tasks synchronized when dispatched asynchronously on different dispatch queues? (Shutterbug example)

StackOverflow https://stackoverflow.com/questions/14283758

  •  15-01-2022
  •  | 
  •  

質問

In the Shutterbug example code presented in Lecture 10, Fall 2011, photos are downloaded and then updated into a table view controller using the following code:

    dispatch_queue_t downloadQueue = dispatch_queue_create("flickr downloader", NULL);
    dispatch_async(downloadQueue, ^{
       NSArray *photos = [FlickrFetcher recentGeoreferencedPhotos];
       dispatch_async(dispatch_get_main_queue(), ^{
          self.navigationItem.rightBarButtonItem = sender;
          self.photos = photos;
          });
     });
     dispatch_release(downloadQueue);

The photo fetching activity is dispatched asynchronously on the flickr downloader queue, and the table view update code (UIKit functionality) is dispatched asynchronously on the main_queue as discussed in class.

What I don't understand is the mechanism which ensures the table view update code on the main_queue is not executed until after the photo fetch activity completes.In the code block, the queues are serially dispatched but I'm not getting how the system knows to not execute the task on the main_queue until after the photo download completes. If this didn't occur, self.photos would be nil if the main_queue task ran before the photo download completed.

役に立ちましたか?

解決

Hm. My original answer here was totally wrong, I apparently misread the code snippet. The reason the view update code doesn't run until after that photos are fetched is that -recentGeoreferencedPhotos is not asynchronous. The dispatch_async doesn't start things being async until the program reaches it, so -recentGeoreferencedPhotos has already returned by that point.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top