To showcase how each Simulator in Ascent can run on a separate thread, we'll run the Control example with different proportional gains, but all at the same time on separate threads..
MultiThread.h
#pragma once
#include "examples/control/Control.h"
#include <thread>
class MultiThread
{
public:
std::vector<cmt::Link<Control>> modules;
MultiThread()
{
for (size_t i = 0; i < 4; ++i) // i is the thread/simulator number
{
asc::Link<Control> c(i);
c->name<Control>("control" + std::to_string(i));
c->Kp = 100.0 * (1 + i); // Each thread will run a separate proportional gain.
c->Ki = 300.0;
c->Kd = 10.0;
c->x_target = 1.0;
c->track("t");
c->track("x");
c->track("x_target");
modules.push_back(c);
}
}
void compute(asc::Link<Control>& control, const double dt, const double tend)
{
control->run(dt, tend);
control->outputTrack();
std::cout << control->name() << " finished\n";
}
void run(const double dt, const double tend)
{
std::vector<std::thread> threads;
for (asc::Link<Control>& c : modules)
threads.push_back(std::thread([&] { compute(c, dt, tend); }));
for (std::thread& t : threads)
t.join();
}
};
Initializing and Running:
Main.cpp
#include "MultiThread.h"
int main()
{
MultiThread multithread;
multithread.run(0.01, 1.0);
return 0;
}