Skip to content

Instantly share code, notes, and snippets.

@jl
Last active December 15, 2015 05:48
Show Gist options
  • Save jl/5211245 to your computer and use it in GitHub Desktop.
Save jl/5211245 to your computer and use it in GitHub Desktop.

Notes on Grand Central Dispatch

This document assumes ARC and Obj-C as of iOS 6.1 and Xcode 4.6.

In Obj-C, GCD will automatically retain objects, including self. In C++, you have to do this yourself for EVERY non-copied object referenced by a dispatch_async block.

#include <memory>
class Foo : std::enable_shared_from_this<Foo> {
 public:
  void DoAsyncWork() {
    std::shared_ptr<Foo> self(shared_from_this());
    dispatch_async(queue_, ^{
      // Reference self at least one time so it gets captured.
      self->InternalWork();
    });
  }
  
  void DoAsyncWorkWithParams(const std::string& unsafe_s, std::shared_ptr<Bar> bar) {
    // We must copy contents of string reference because we don't control
    // its value after this function returns while the async block is running.
    // It would probably be better just to specify std::string instead of
    // const std::string& as a parameter if you know it will be used in the block.
    std::string s_copy(unsafe_s);
    dispatch_async(queue_, ^{
      // The following references will cause s and bar to be
      // copied into the closure block. Be sure this is what you want.
      // For example, s should always be a small string.
      Log(s_copy);
      bar->Ok();
    });
  }
  
 private:
  void InternalWork();
  
  dispatch_queue_t queue_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment