Honeycomb  0.1
Component-Model Framework
Backoff.h
Go to the documentation of this file.
1 // Honeycomb, Copyright (C) 2015 NewGamePlus Inc. Distributed under the Boost Software License v1.0.
2 #pragma once
3 
4 #include "Honey/Thread/Thread.h"
5 
6 namespace honey { namespace lockfree
7 {
8 
10 class Backoff
11 {
12 public:
13 
20  Backoff(bool spin = true, Nanosec timeMin = 100_ns, Nanosec timeMax = 100_us, int tickThresh = 5) :
21  _spin(spin),
22  _timeMin(timeMin),
23  _timeMax(timeMax),
24  _tickThresh(tickThresh)
25  {}
26 
28  void inc(int ticks = 1)
29  {
30  Local& l = _l;
31  for (l.tick += ticks; l.tick >= _tickThresh; l.tick -= _tickThresh)
32  {
33  //Deactivate spin
34  if (l.spin) { l.spin = false; continue; }
35  //Grow sleep time
36  l.time = l.time*2 + 1_ns;
37  if (l.time > _timeMax) l.time = _timeMax;
38  }
39  }
40 
42  void dec(int ticks = 1)
43  {
44  Local& l = _l;
45  for (l.tick -= ticks; l.tick <= -_tickThresh; l.tick += _tickThresh)
46  {
47  //Activate spin
48  if (l.time == _timeMin) { l.spin = _spin; continue; }
49  //Shrink sleep time
50  l.time = l.time/2;
51  if (l.time < _timeMin) l.time = _timeMin;
52  }
53  }
54 
56  void wait() { Local& l = _l; if (l.spin) thread::current::pause(); else thread::current::sleep(l.time); }
57 
59  void reset() { Local& l = _l; l.spin = _spin; l.time = _timeMin; l.tick = 0; }
60 
61 private:
62 
63  struct Local
64  {
65  bool spin;
66  Nanosec time;
67  int tick;
68  };
69 
70  bool _spin;
71  Nanosec _timeMin;
72  Nanosec _timeMax;
73  int _tickThresh;
75 };
76 
77 } }
void inc(int ticks=1)
Increase tick count by ticks. Increases the amount of time that backoff will wait.
Definition: Backoff.h:28
void spin(int count)
Suspend this thread momentarily without giving up its time slice. The thread will pause count times...
Definition: Thread.h:60
void pause()
Perform a no-op without giving up this thread's time slice. This no-op momentarily frees resources fo...
Definition: Thread.h:54
void sleep(MonoClock::Duration time)
Suspend this thread for an amount of time.
Definition: Thread.cpp:35
Exponential backoff algorithm. Backoff spins for first X ticks, then sleeps with a time that doubles ...
Definition: Backoff.h:10
Backoff(bool spin=true, Nanosec timeMin=100_ns, Nanosec timeMax=100_us, int tickThresh=5)
Definition: Backoff.h:20
void wait()
Perform backoff, suspend thread.
Definition: Backoff.h:56
void reset()
Reset backoff to initial state.
Definition: Backoff.h:59
Global Honeycomb namespace.
void dec(int ticks=1)
Decrease tick count by ticks. Decreases the amount of time that backoff will wait.
Definition: Backoff.h:42