title: Multithreading in Direct2D
body: <p>I'm trying to create a simple D2D game engine (it must be able to display and move images in a window, at least), and everything went right until the moment when I decided to switch to the multithreaded version. I read <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/jj569217%28v=vs.85%29.aspx" rel="nofollow">this</a> MSDN article, and it recommends using one multithreaded factory from several threads. But <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ff485857%28v=vs.85%29.aspx#multithreading" rel="nofollow">this</a> article claims it would be more effective to have several single-threaded factories (though the article describes server-side rendering scenario, the principle is the same for my case, am I wrong?). When I tried to use one-thread-one-factory approach, all the images are displayed and moved, but there's terrible flickering. In my WM_PAINT handler I'm trying to do something like this:</p>
  
  <pre><code>for (CSingleThreadEngine *pElSingleThreadEngine : m_SingleThreadEngines) //each CSingleThreadEngine instance has its own D2D factory and an image collection
      pElSingleThreadEngine-&gt;Draw();
  </code></pre>
  
  <p>and pElSingleThreadEngine->Draw() does drawing like this:</p>
  
  <pre><code>m_pRenderTarget-&gt;BeginDraw();
  m_pRenderTarget-&gt;SetTransform(D2D1::Matrix3x2F::Identity());
  m_pRenderTarget-&gt;Clear(D2D1::ColorF(D2D1::ColorF::White));
  for (CGameImage *pImage : m_GameImages)
  {
      if (FAILED(pImage-&gt;Draw()))
          throw runtime_error("An object cannot be drawn");
  }
  m_pRenderTarget-&gt;EndDraw();
  </code></pre>
  
  <p>I think the wrong thing here is having several ID2D1HwndRenderTarget instances for just one window because if I make drawing each thread in a separate window, it works just fine. But I want to draw in one window only, and I can't avoid using multiple ID2D1HwndRenderTarget instances for this purpose. So my questions are:</p>
  
  <ol>
  <li>What are the best practices for creating multithreaded Direct2D applications at all?</li>
  <li>If the approach I'm using is right, what am I doing wrong and how can I fix it?</li>
  </ol>
  
  <p>Any help would be highly appreciated.</p>