title: C++: Error handling problem across threads
body: <p>In general I use exceptions to deal with errors, however the problem I have here is that the error applies to a different thread than the one that caused it.</p>
  
  <p>Basicly the window has its own thread, and the direct3d device must be created and reset by the same thread that created the window. However creating the device may fail, so I need to throw an exception in the thread that was trying to create the instance, not the window code</p>
  
  <p>The callback function:</p>
  
  <pre><code>void Callback(HWND hwnd, boost::function&lt;void(HWND,LPARAM)&gt; call, LPARAM lParam)
  {
      //Make our stack allocated function object into a heap allocated one
      boost::function&lt;void(HWND,LPARAM)&gt; *callH = new boost::function&lt;void(HWND,LPARAM)&gt;(call);
      //send a message with a pointer to our function object in the WPARAM
      PostMessage(hwnd, WM_CALLBACK, (unsigned)callH, lParam);
  }
  LRESULT CALLBACK HookProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  {
      //check for our custom message
      if(msg == WM_CALLBACK)
      {
          //retreive the function pointer from the WPARAM
          boost::function&lt;void(HWND,LPARAM)&gt; *callH = (boost::function&lt;void(HWND,LPARAM)&gt;*)wParam;
          //call it
          (*callH)(hwnd,lParam);
          //delete our heap allocated function object
          delete callH;
          return 0;
      }
      else
          //if there was nothing relevant to us, call the old message procedure
          return CallWindowProc(hooked[hwnd], hwnd, msg, wParam, lParam);
  }
  //std::map&lt;HWND, WNDPROC&gt; hooked;
  </code></pre>
  
  <p>The code that requests the window thread to create the device</p>
  
  <pre><code>Graphics::Graphics(IWindow *_window, Size2&lt;unsigned&gt; _size)
  :lost(false), reset(false), refCnt(0), backCol(0xFF000000),
  started(false), exited(false),
  window(_window), size(_size)
  {
      window-&gt;AddRef();
      HWND hwnd = *((HWND*)window-&gt;GetHandle());
      CallbackHook(hwnd);
      Callback(hwnd, boost::bind(&amp;Graphics::create, this), 0);
  
      while(!started)Sleep(100);
  }
  void Graphics::create()
  {
  ...code that may throw various exceptions
      started = true;
  }
  </code></pre>
  
  <p>So basically I need the exceptions being thrown by the create() method to be caught by the exception handelers where the Graphics object was created which is another thread.</p>