lsnes rr2-β23
[lsnes.git] / include / library / triplebuffer.hpp
blob2573f46b0e097323990a57bf3a5cec01ff7aefce
1 #ifndef _library_triplebuffer__hpp__included__
2 #define _library_triplebuffer__hpp__included__
4 #include <stdexcept>
5 #include "threads.hpp"
7 namespace triplebuffer
9 /**
10 * Triple-buffering logic.
12 class logic
14 public:
15 /**
16 * Create a new triple buffer.
18 logic() throw();
19 /**
20 * Get read pointer and increment read count by 1.
22 * Return value: Read pointer (0-2).
24 * Note: If read count is zero, last complete buffer is returned. Otherwise the same buffer as last call is returned.
26 unsigned get_read() throw();
27 /**
28 * Put read pointer and decrement read count by 1.
30 * Throws std::logic_error: If read count is 0.
32 void put_read() throw(std::logic_error);
33 /**
34 * Get write pointer and increment write count by 1.
36 * Return value: Write pointer (0-2).
38 * Note: If write count is nonzero before call, the returned buffer is the same as last time.
40 unsigned get_write() throw();
41 /**
42 * Put write pointer and decrement write count by 1. If write count hits 0, the buffer is marked as last complete
43 * buffer.
45 * Throws std::logic_error: If write count is 0.
47 void put_write() throw(std::logic_error);
48 private:
49 threads::lock lock;
50 unsigned last_complete; //Number of last completed buffer
51 unsigned current_read; //Number of current read buffer (only valid if count_read > 0).
52 unsigned current_write; //Number of current write buffer (only valid if count_write > 0).
53 unsigned count_read; //Number of readers.
54 unsigned count_write; //Number of writers.
57 /**
58 * Triple buffer with objects.
60 template<typename T>
61 class triplebuffer
63 public:
64 /**
65 * Create a new triple buffer.
67 * Parameter A: Object #1.
68 * Parameter B: Object #2.
69 * Parameter C: Object #3.
71 triplebuffer(T& A, T& B, T& C) throw()
73 objs[0] = &A;
74 objs[1] = &B;
75 objs[2] = &C;
77 /**
78 * Get read pointer and increment read count by 1.
80 * Return value: Read pointer.
82 * Note: If read count is zero, last complete buffer is returned. Otherwise the same buffer as last call is returned.
84 T& get_read() throw() { return *objs[l.get_read()]; }
85 /**
86 * Put read pointer and decrement read count by 1.
88 * Throws std::logic_error: If read count is 0.
90 void put_read() throw(std::logic_error) { l.put_read(); }
91 /**
92 * Get write pointer and increment write count by 1.
94 * Return value: Write pointer.
96 * Note: If write count is nonzero before call, the returned buffer is the same as last time.
98 T& get_write() throw() { return *objs[l.get_write()]; }
99 /**
100 * Put write pointer and decrement write count by 1. If write count hits 0, the buffer is marked as last complete
101 * buffer.
103 * Throws std::logic_error: If write count is 0.
105 void put_write() throw(std::logic_error) { l.put_write(); }
106 private:
107 T* objs[3];
108 logic l;
112 #endif