title: Creating a friendly timed busy loop for a hyperthread
body: <p>Imagine I want to have one <em>main thread</em> and a <em>helper thread</em> run as the two hyperthreads on the same physical core (probably by forcing their affinity to approximately ensure this).</p>
  
  <p>The <em>main thread</em> will be doing important high IPC, CPU-bound work. The <em>helper thread</em> should do nothing other than periodically updating a shared timestamp value that the the main thread will periodically read. The update frequency is configurable, but could be as fast as 100 MHz or more. Such fast updates more or less rule out a sleep-based approach, since blocking sleeps are too slow to sleep/wake on a 10 nanosecond (100 MHz) period.</p>
  
  <p>So I want a busy wait. However, the busy wait should be as <em>friendly</em> as possible to the main thread: use as few execution resources as possible, and so add as little overhead as possible to the main thread.</p>
  
  <p>I guess the idea would be a long-latency instruction that doesn't use many resources, like <code>pause</code> and that also has a fixed-and-known latency. That would let us calibrate the "sleep" period so no clock read is even needed (if want to update with period <code>P</code> we just issue <code>P/L</code> of these instructions for a calibrated busy-sleep. Well <code>pause</code> doesn't meet that latter criterion, as its latency varies a lot<sup>1</sup>.</p>
  
  <p>A second option would be to use a long-latency instruction even if the latency is unknown, and after every instruction do a <code>rdtsc</code> or some other clock reading method (<code>clock_gettime</code>, etc) to see how long we actually slept. Seems like it might slow down the main thread a lot though.</p>
  
  <p>Any better options?</p>
  
  <hr>
  
  <p><sup>1</sup> Also <code>pause</code> has some specific semantics around preventing speculative memory accesses which may or may not be beneficial to this sibling thread scenario, since I'm not in a spin-wait loop really.</p>