title: Asynchronous Procedure Calls
body: <p>I'm trying to get <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms681951%28v=vs.85%29.aspx" rel="noreferrer">APC</a> to work in my C++ code but I fail. I'm lost for words. In C# it works all fine (logically the same code). I want thread 2 to inject a call into thread 1. But in my C++ project it wont execute for some reason. What am I doing wrong ?</p>
  
  <ul>
  <li>thread 1 (main thread)</li>
  <li>thread 2 (sub thread, that needs the main thread to execute a function)</li>
  </ul>
  
  <p><hr>
  <strong>Code:</strong></p>
  
  <pre><code>#include "stdio.h"
  #include "windows.h"
  
  #define TIME 2500
  #define LAST_ERROR printf("last error: %i\r\n", GetLastError());
  
  HANDLE handle1, handle2;
  
  void ThreadInfo(char* prefix = "")
  {
      printf("%sthread id: %i\r\n", prefix, GetCurrentThreadId());
  }
  
  VOID CALLBACK apc( _In_ ULONG_PTR data)
  {
      ThreadInfo(" -&gt; apc: 2 -&gt; 1: ");
  }
  
  void run1()
  {
      while (true)
      {
          Sleep(TIME);
          ThreadInfo("1: ");
  
          // apc
          //QueueUserAPC(apc, handle2, (ULONG_PTR) NULL);
      }
  }
  
  void run2()
  {
      while (true)
      {
          Sleep(TIME);
          ThreadInfo("2: ");
  
          // apc
          QueueUserAPC(apc, handle1, (ULONG_PTR) NULL);
      }
  }
  
  void TestThreads()
  {
      DWORD threadId;
      SECURITY_ATTRIBUTES a;
      a.nLength = 12;
      a.lpSecurityDescriptor = NULL;
      a.bInheritHandle = 1;
  
      DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &amp;handle1, 0, true, 2);
      LAST_ERROR
  
      handle2 = CreateThread(NULL, 100000, (LPTHREAD_START_ROUTINE)run2, NULL, 0, &amp;threadId);
      printf("handles (1, 2): %i, %i\r\n", handle1, handle2);
      printf("ids (1, 2): %i, %i\r\n", threadId, GetCurrentThreadId());
      printf("--------------------------------\r\n");
      run1();
  }
  
  int main()
  {
      TestThreads();
  
      printf("done.");
      getchar();
      return 0;
  }
  </code></pre>