title: GetThreadContext fails after a successful SuspendThread in Windows 7
body: <p>I'm encountering an odd issue on a sampling profiler in Windows 7 (no such issues AFAICT on previous Windows OSes, be they 32 or 64 bit).</p>
  
  <p>The profiler works by periodically suspending a thread with <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms686345(v=vs.85).aspx" rel="nofollow noreferrer"><code>SuspendThread</code></a>, then looks at the context with <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms679362(v=vs.85).aspx" rel="nofollow noreferrer"><code>GetThreadContext</code></a>, before invoking <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms685086(v=vs.85).aspx" rel="nofollow noreferrer"><code>ResumeThread</code></a> to restart the process. All this is done from the context of the thread of a multimedia timer (for accuracy, at about 1kHZ, which on pre-Windows 7 OSes usually incurs a negligible performance penalty).</p>
  
  <p>Under Windows 7, and Windows 7 only, even though the calls to <code>SuspendThread</code> (and <code>ResumeThread</code>) all succeed, the calls to <code>GetThreadContext</code> fail with error: </p>
  
  <blockquote>
    <p><strong>ERROR_NOACCESS</strong><br>
    998 (0x3E6)<br>
    Invalid access to memory location.</p>
  </blockquote>
  
  <p>with a very high likeliness, though not all the time.  </p>
  
  <p>By that I mean that for some profiling runs, everything will work as it does on other OSes (all the <code>GetThreadContext</code> calls will succeed), but for other runs, they will almost all fail (save a dozen maybe, out of tens of thousandths). It's happening with the exact same binaries, the same parameters.</p>
  
  <p>I've tried suggestions on vaguely similar looking issues to repeat the <code>GetThreadContext</code> call, with no more success. I've also tried doing a <code>Sleep</code> between the <code>SuspendThread</code> and <code>GetThreadContext</code>, then the <code>GetThreadContext</code> succeeds more often, though it results in drastic slowdowns.  </p>
  
  <p>It suggests however that Windows 7 OS is returning from <code>SuspendThread</code> while the thread has probably not been suspended yet - though, if that's the case, I've no idea how or if to properly wait on the suspension, looping in the thread and pounding <code>GetThreadContext</code> doesn't do it.</p>
  
  <p><strong>Edit:</strong> 16 byte aligning the address of the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms679284.aspx" rel="nofollow noreferrer"><code>CONTEXT</code></a> structure for <code>GetThreadContext</code> as suggested by Dan Bartlett seems to be doing the trick!</p>