#include <iostream>
#include <iomanip>
#include <thread>
#include <chrono>
bool flag = true;
int force_data = 0;
void force_sensor()
{
int i = 0;
// Sensor sampling time = 20 ms
while(flag)
{
force_data = i;
std::this_thread::sleep_for(std::chrono::milliseconds(20)); // Sleep for 20 ms
++i;
}
std::cout << "t1: force sensor end." << std::endl;
}
int main(int arc, char *argv[])
{
std::thread t1(force_sensor); // Launch force_sensor_thread
// Read force sensor
int j = 0;
// Motor sampling time = 1 ms
while (j < 1000)
{
std::cout << "[" << std::setw(4) << std::right << j << "] " << "Force_data = " << force_data << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1)); // Sleep for 1 ms
++j;
}
flag = false;
std::cout << "Main: call force_sensor to stop." << std::endl;
t1.join(); // pause for t1 to end
std::cout << "Main: end." << std::endl;
return 0;
}
$ g++ -pthread -o test test.cpp
OS: Linux Ubuntu 20.0.4 LTS
compiler: GNU g++