title: Reusable background thread in MFC
body: <p>I want to create a reusable background thread to queue a number of tasks that require access to a singleton resource. The thread should be created at the start of the program and a message will be sent whenever it is required to complete a task. At first I was trying to use a worker thread, as the background thread doesn't have a UI, but then I noticed that only UI threads have message pumps. Unfortunately, <code>PostThreadMessage</code> always returns <code>ERROR_INVALID_THREAD_ID</code>, but I am sure the thread has been created correctly.</p>
  
  <ol>
  <li>Is it a good choice to use a UI thread rather than a worker thread?</li>
  <li>Why isn't my <code>PostThreadMessage</code> being received?</li>
  </ol>
  
  <p><strong>UPDATE</strong>: By looking at the output messages, I now know that the message isn't being received because the thread is killed</p>
  
  <p>Sample code</p>
  
  <pre><code>DWORD deviceControllerThread;
  
  void post(){
      BOOL res=PostThreadMessage(deviceControllerthread,ControllerThread, ENROLLMENT_BEGIN, (WPARAM) myDataPointer, 0);
      ...
  }
  
  void MFC_Init(){
      CWinThread* thread=AfxBeginThread(RUNTIME_CLASS(MFC_thread), THREAD_PRIORITY_NORMAL, 0, 0);
      deviceControllerThread=thread-&gt;m_nThreadID;
  }
  </code></pre>