c++ - what is the fastest way to notify another thread that data is available? any alternativies to spinning? -


one thread writes data circular-buffer , thread need process data asap. thinking write such simple spin. pseudo-code!

    while (true) {         while (!a[i]) {             /* nothing - keep checking on , on */         }         // process b[i]         i++;         if (i >= max_length) {             = 0;         }     } 

above i'm using a indicate data stored in b available processing. probaly should set thread afinity such "hot" process. of course such spin expensive in terms of cpu it's ok me primary requirement latency.

the question - should write or boost or stl allows that:

  1. easier use.
  2. has same (or better?) latency @ same time occupying less cpu resources?

i think pattern general there should implementation somewhere.

upd seems question still complicated. let's consider case when need write items array in arbitrary order , thread should read them in right order items available, how that?

upd2

i'm adding test program demonstrate , how want achive. @ least on machine happens work. i'm using rand show can not use general queue , need use array-based structure:

#include "stdafx.h" #include <string> #include <boost/thread.hpp> #include "windows.h" // sleep   const int buffer_length = 10; int buffer[buffer_length]; short flags[buffer_length];  void processorthread() {     (int = 0; < buffer_length; i++) {         while (flags[i] == 0);         printf("item %i received, value = %i\n", i, buffer[i]);     } }   int _tmain(int argc, _tchar* argv[]) {     memset(flags, 0, sizeof(flags));     boost::thread processor = boost::thread(&processorthread);     (int = 0; < buffer_length * 10; i++) {         int x = rand() % buffer_length;         buffer[x] = x;         flags[x] = 1;         sleep(100);     }     processor.join();     return 0; } 

output:

item 0 received, value = 0 item 1 received, value = 1 item 2 received, value = 2 item 3 received, value = 3 item 4 received, value = 4 item 5 received, value = 5 item 6 received, value = 6 item 7 received, value = 7 item 8 received, value = 8 item 9 received, value = 9 

is program guaranteed work? how redesign it, using of existent structures boost/stl instead of array? possible rid of "spin" without affecting latency?

if consuming thread put sleep takes few microseconds wake up. process scheduler latency cannot avoid unless thread busy-spinning do. thread needs real-time fifo never put sleep when ready run exhausted time quantum.

so, there no alternative match latency of busy spinning.

(surprising using windows, best avoided if serious hft).


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -