title: Thread-Safe Game Engine: Multi-Threading Best Practices?
body: <p>I'm writing a multi-threaded game engine, and I'm wondering about best practices around waiting for threads. It occurs to me that there could be much better options out there than what I've implemented, so I'm wondering what you guys think.</p>
  
  <p><strong>Option A)</strong> "wait()" method gets called at the top of every other method in the class. This is my current implementation, and I'm realizing it's not ideal.</p>
  
  <pre><code>class Texture {
  public:
      Texture(const char *filename, bool async = true);
      ~Texture();
  
      void Render();
  
  private:
      SDL_Thread *thread;
      const char *filename;
  
      void wait();
      static int load(void *data);
  }
  
  void Texture::wait() {
      if (thread != NULL) {
          SDL_WaitThread(thread, NULL);
          thread = NULL;
      }
  }
  
  int Texture::load(void *data) {
      Texture *self = static_cast&lt;Texture *&gt;(data);
  
      // Load the Image Data in the Thread Here...
  
      return 0;
  }
  
  Texture::Texture(const char *filename, bool async) {
      this-&gt;filename = filename;
      if (async) {
          thread = SDL_CreateThread(load, NULL, this);
      } else {
          thread = NULL;
          load(this);
      }
  }
  
  Texture::~Texture() {
      // Unload the Thread and Texture Here
  }
  
  void Texture::Render() {
      wait();
  
      // Render the Texture Here
  }
  </code></pre>
  
  <p><strong>Option B)</strong> Convert the "wait()" method in to a function pointer. This would save my program from a jmp at the top of every other method, and simply check for "thread != NULL" at the top of every method. Still not ideal, but I feel like the less jumps, the better. (I've also considered just using the "inline" keyword on the function... but would this include the entire contents of the wait function when all I really need is the "if (thread != NULL)" check to determine whether the rest of the code should be executed or not?)</p>
  
  <p><strong>Option C)</strong> Convert all of the class' methods in to function pointers, and ditch the whole concept of calling "wait()" except while actually loading the texture. I see advantages and disadvantages to this approach... namely, this feels the most difficult to implement and keep track of. Admittedly, my knowledge of the inner workings on GCC's optimizations and assembly and especially memory->cpu->memory communication isn't the best, so using a bunch of function pointers might actually be slower than a properly defined class.</p>
  
  <p>Anyone have any even better ideas?</p>