title: C++ threading to download
body: <p>I need help with C++ threading stuff, I have created a dll which has a exported function as downloadfile (to download a file from the internet). This function in turns create a thread to download a file (the function used to download a file is blocking function i.e. URLDownloadToFile that's why I put the download functionality on thread). </p>
  
  <p>I want to achieve following.</p>
  
  <ol>
  <li><p>my call to downloadfile function should not block the main thread.</p></li>
  <li><p>I want to download more than one file at a time.</p></li>
  </ol>
  
  <p>remember that, download functionality is in the dll created in C++ and this dll will be used in Pascal.</p>
  
  <p>following is the code snippet:</p>
  
  <pre><code>struct DOWNLOADPARAM
  {
      HANDLE hEventStop;
      TCHAR *szURL;
      TCHAR *szFilePath;
  };
  
  
  DWORD WINAPI Transfer(void *hw)
  {
      Mutex mutex_;
  
      DOWNLOADPARAM *const pDownloadParam = static_cast&lt;DOWNLOADPARAM *&gt;(hw);
      CBSCallbackImpl bsc(NULL, pDownloadParam-&gt;hEventStop);
  
  
             const HRESULT hr = ::URLDownloadToFile(NULL,pDownloadParam-&gt;szURL  ,pDownloadParam-&gt;szFilePath,0,&amp;bsc);
  
  
      return 0;
  }
  
  
  extern "C" void  __declspec(dllexport)   downloadfile(TCHAR *url, TCHAR *dest)
  {
      Mutex mutex_;
  
      DWORD dwThreadId;
      DOWNLOADPARAM *obj = new DOWNLOADPARAM();
      obj-&gt;szURL      = url;
      obj-&gt;szFilePath = dest;
  
  
      if((hThread = CreateThread(NULL, 0, Transfer, (LPVOID)obj, 0,&amp;dwThreadId)) != NULL)
      {
      }
  
  
  // Following code block the thread untill finished 
  
      WaitForSingleObject(hThread, INFINITE);
          TerminateThread(hThread, 0);
      CloseHandle(hThread);
  }
  </code></pre>