A sensor driver, an MQTT client or a camera usually receives its data on a thread of its own, while the controller runs on another. The data has to pass from one thread to the other without being lost or read half written. ConcurrentQueue does that: one thread pushes, another pops, and the pop waits for data when there is none. bitsim's MqttSubscriber keeps the messages it receives in one.
Here a simulated gyroscope produces a turn rate every 5 ms for 2 s on its own thread, and an estimator integrates the rates into a heading on the main thread.
What you need
Nothing beyond bitsim itself. See Installing bitsim.
The queue
ConcurrentQueue<GyroReading> queue;
queue.push({k, k * PERIOD, rate});
...
queue.close();
auto reading = queue.pop_for(20ms);
| |
| push(x) | adds x at the back; returns false, and drops x, once the queue is closed |
| pop() | waits until there is an item, or the queue is closed and empty |
| pop_for(timeout) | waits at most timeout |
| try_pop() | does not wait |
| close() | wakes every thread that waits; they get what is left, then std::nullopt |
Running the example
Output
1. A consumer that keeps up
fast estimator: 400 readings in 2.00 s, heading 1.0006 rad (true 1.0000), at most 0 readings waiting, 0 waits timed out
2. A consumer that falls behind
slow estimator: 400 readings in 3.24 s, heading 1.0006 rad (true 1.0000), at most 152 readings waiting, 0 waits timed out
3. Draining what is there
try_pop took 5 readings without waiting; after close(), push() gives false
The fast estimator takes each reading as it arrives, so the queue never holds more than the reading being taken. The slow one needs 8 ms per reading, longer than the 5 ms between them: the readings pile up, up to 152 of them, and the estimate is 1.2 s late, but no reading is lost and the heading is the same. A real controller that falls behind like that should drain the queue with try_pop() and use the newest reading, as part 3 does, rather than work through stale ones.
The waits of pop_for would time out if the sensor stopped sending; here it never does. When it is done, close() tells the estimator, which stops once the queue is empty.
Things to try
- Stop the sensor after 1 s without closing the queue. How does the estimator notice?
- Run two estimators on two threads, popping from the same queue. Which readings does each get, and what is the heading of each?
- Make the slow estimator drain the queue and integrate only the newest reading, scaled by the time since the last one it used.
The code
#include <algorithm>
#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <random>
#include <thread>
{
using namespace std::chrono_literals;
struct GyroReading
{
};
void sensor(ConcurrentQueue<GyroReading> &queue)
{
std::mt19937 rng(7);
std::normal_distribution<real_t> noise(0.0, 0.02);
const auto start = clock_type::now();
{
std::this_thread::sleep_until(start + std::chrono::duration<real_t>(k *
PERIOD));
}
queue.close();
}
{
};
{
while (true)
{
auto reading = queue.pop_for(20ms);
if (!reading)
{
if (queue.is_closed() && queue.empty())
{
break;
}
++e.n_timeouts;
continue;
}
e.heading += reading->rate *
PERIOD;
++e.n_readings;
e.max_backlog = std::max(e.max_backlog, queue.size());
std::this_thread::sleep_for(work_per_reading);
}
return e;
}
{
std::cout << " " << name << ": " << e.n_readings << " readings in " << std::fixed
<< std::setprecision(2) <<
seconds <<
" s, heading " << std::setprecision(4)
<< e.max_backlog << " readings waiting, " << e.n_timeouts << " waits timed out\n";
}
void run_with(
const std::string &name, std::chrono::microseconds work_per_reading)
{
const auto start = clock_type::now();
std::thread producer(
sensor, std::ref(queue));
producer.join();
report(name, e, std::chrono::duration<real_t>(clock_type::now() - start).count());
}
{
std::cout << "\n";
std::cout << "\n";
for (
uint_t k = 0; k < 5; ++k)
{
}
while (queue.try_pop())
{
++drained;
}
queue.close();
std::cout << " try_pop took " << drained << " readings without waiting; after close(), push() "
<< "gives " << std::boolalpha << queue.push({5, 0.0, 0.0}) << "\n";
}
}
{
return 0;
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
A first-in first-out queue that several threads can push to and pop from.
Definition concurrent_queue.h:26
int main()
Definition discounted_returns.cpp:19
void print_title(const std::string &title, std::ostream &out)
An empty line and then the title.
Definition print_utils.cpp:17
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
real_t seconds(steady::duration d)
Definition ppo_distributed.cpp:188
Definition producer_consumer.cpp:24
const real_t TRUE_RATE
Definition producer_consumer.cpp:42
std::chrono::steady_clock clock_type
Definition producer_consumer.cpp:29
Estimate estimator(ConcurrentQueue< GyroReading > &queue, std::chrono::microseconds work_per_reading)
Definition producer_consumer.cpp:68
const real_t PERIOD
Definition producer_consumer.cpp:40
void sensor(ConcurrentQueue< GyroReading > &queue)
Definition producer_consumer.cpp:45
void run_with(const std::string &name, std::chrono::microseconds work_per_reading)
Definition producer_consumer.cpp:100
const uint_t N_READINGS
Definition producer_consumer.cpp:41
void run()
Definition producer_consumer.cpp:110
void report(const std::string &name, const Estimate &e, real_t seconds)
Definition producer_consumer.cpp:92
Print labelled values, one per line, as the examples do: two spaces, the label padded to a width,...
Definition producer_consumer.cpp:60
uint_t n_timeouts
Definition producer_consumer.cpp:64
real_t heading
Definition producer_consumer.cpp:62
std::size_t max_backlog
Definition producer_consumer.cpp:63
uint_t n_readings
Definition producer_consumer.cpp:61
real_t rate
Definition producer_consumer.cpp:37
real_t time
Definition producer_consumer.cpp:36
uint_t index
Definition producer_consumer.cpp:35