Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to have a thread wait for a value to change in memory?

For some silly reason, there's a piece of hardware on my (GNU/Linux) machine that can only communicate a certain occurrence by writing a value to memory. Assume that by some magic, the area of memory the hardware writes to is visible to a process I'm running. Now, I want to have a thread within that process keep track of that value, and as soon as possible after it has changed - execute some code. However, it is more important to me that the thread not waste CPU time than for it to absolutely minimize the response delay. So - no busy-waiting on a volatile...

How should I best do this (using modern C++)?

Notes:

  • I don't mind a solution involving atomics, or synchronization mechanisms (in fact, that would perhaps be preferable) - as long as you bear in mind that the hardware doesn't support atomic operations on host memory - it performs a plain write.
  • The value the hardware writes can be whatever I like, as can the initial value in the memory location it writes to.
  • I used C++11 since it's the popular tag for Modern C++, but really, C++14 is great and C++17 is ok. On the other hand, even a C-based solution will do.
like image 706
einpoklum Avatar asked Nov 18 '22 16:11

einpoklum


1 Answers

So, the naive thing to do would be non-busy sleeping, e.g.:

volatile int32_t* special_location = get_special_location();
auto polling_interval_in_usec = perform_tradeoff_between_accuracy_and_cpu_load();
auto polling_interval = std::chrono::microseconds(polling_interval_in_usec);

while(should_continue_polling()) {
    if (*special_location == HardwareIsDone) { 
         do_stuff();
         return;
    }
    std::this_thread::sleep_for(polling_interval); 
}
like image 73
einpoklum Avatar answered Dec 18 '22 13:12

einpoklum