bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
A sensor thread and a queue

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;
// the sensor thread
queue.push({k, k * PERIOD, rate});
...
queue.close(); // nothing more is coming
// the estimator
auto reading = queue.pop_for(20ms); // std::nullopt if nothing came in 20 ms
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

./producer_consumer

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

  1. Stop the sensor after 1 s without closing the queue. How does the estimator notice?
  2. Run two estimators on two threads, popping from the same queue. Which readings does each get, and what is the heading of each?
  3. 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

// A gyroscope on one thread, a heading estimator on another, and a ConcurrentQueue between them.
//
// The sensor thread produces a reading of the turn rate every 5 ms for 2 s, the way a driver or
// an MQTT client receives messages on a thread of its own. The estimator takes the readings from
// the queue and integrates them into a heading. A second, slow estimator shows the queue filling
// up when the consumer cannot keep up, and close() shows how the producer tells the consumer that
// nothing more is coming.
//
// Usage: producer_consumer
#include <algorithm>
#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <random>
#include <thread>
{
using clock_type = std::chrono::steady_clock;
using namespace std::chrono_literals;
// One reading of the gyroscope
struct GyroReading
{
real_t time; // [s]
real_t rate; // [rad/s]
};
const real_t PERIOD = 0.005; // a reading every 5 ms
const uint_t N_READINGS = 400; // for 2 s
const real_t TRUE_RATE = 0.5; // the robot turns at 0.5 rad/s
// Produce N_READINGS readings at the sensor's rate, then close the queue
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();
for (uint_t k = 0; k < N_READINGS; ++k)
{
std::this_thread::sleep_until(start + std::chrono::duration<real_t>(k * PERIOD));
queue.push({k, k * PERIOD, TRUE_RATE + noise(rng)});
}
// nothing more is coming: a consumer waiting in pop() wakes up empty handed
queue.close();
}
struct Estimate
{
std::size_t max_backlog{0};
};
// Integrate the readings into a heading; work_per_reading makes the consumer slower
Estimate estimator(ConcurrentQueue<GyroReading> &queue, std::chrono::microseconds work_per_reading)
{
while (true)
{
// wait at most 20 ms for a reading, so that a dead sensor would be noticed
auto reading = queue.pop_for(20ms);
if (!reading)
{
if (queue.is_closed() && queue.empty())
{
break; // the sensor is done
}
++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;
}
void report(const std::string &name, const Estimate &e, real_t seconds)
{
std::cout << " " << name << ": " << e.n_readings << " readings in " << std::fixed
<< std::setprecision(2) << seconds << " s, heading " << std::setprecision(4)
<< e.heading << " rad (true " << TRUE_RATE * N_READINGS * PERIOD << "), at most "
<< 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));
const Estimate e = estimator(queue, work_per_reading);
producer.join();
report(name, e, std::chrono::duration<real_t>(clock_type::now() - start).count());
}
void run()
{
bitsim::utils::io::print_title("1. A consumer that keeps up");
// 0.1 ms of work per reading, well within the 5 ms between readings
run_with("fast estimator", 100us);
std::cout << "\n";
bitsim::utils::io::print_title("2. A consumer that falls behind");
// 8 ms of work per reading: the readings pile up in the queue, none is lost, and the
// estimate is late but the same
run_with("slow estimator", 8ms);
std::cout << "\n";
bitsim::utils::io::print_title("3. Draining what is there");
for (uint_t k = 0; k < 5; ++k)
{
queue.push({k, k * PERIOD, TRUE_RATE});
}
uint_t drained = 0;
// try_pop never waits: take everything that has arrived, then go on with the control loop
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";
}
} // namespace producer_consumer
int main()
{
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