我正在为一个非常简单的机器人构建一个模拟器来测试学生代码。我需要以固定的时间间隔在单独的线程上运行两个功能(更新机器人传感器和机器人位置)。我目前的实现是处理器效率很低的,因为它有一个线程专门用于简单地递增数字来跟踪代码中的位置。我最近的理论是,我可以使用睡眠来给出传感器更新值和机器人位置之间的时间延迟。我的第一个问题是:这有效吗?第二:有没有什么方法可以做一件简单的事情,但测量时钟周期而不是秒?
通过等待类似互斥对象来使线程进入睡眠状态通常是有效的。一种常见的模式是等待一个有超时的互斥对象。当达到超时时,时间间隔就到了。当互斥对象被关联时,它是线程终止的信号。
伪码:
void threadMethod() {
for(;;) {
bool signalled = this->mutex.wait(1000);
if(signalled) {
break; // Signalled, owners wants us to terminate
}
// Timeout, meaning our wait time is up
doPeriodicAction();
}
}
void start() {
this->mutex.enter();
this->thread.start(threadMethod);
}
void stop() {
this->mutex.leave();
this->thread.join();
}
在Windows系统上,超时通常以毫秒为单位,精确到大约16毫秒以内(timeBeginPeriod()
可能能够改进这一点)。我不知道CPU周期触发的同步原语。有一种称为"关键部分"的轻量级互斥,在委派给操作系统线程调度程序之前,它会使CPU旋转几千个周期。在这段时间内,它们是相当准确的。
在Linux系统上,精度可能会更高一点(高频定时器或无提示内核),除了互斥之外,还有类似于Windows关键部分的"futexes"(快速互斥)。
我不确定我是否掌握了你想要实现的目标,但如果你想测试学生代码,你可能想使用虚拟时钟并自己控制时间的流逝。例如,通过调用学生必须提供的processInputs()
和decideMovements()
方法。每次通话后,会有一个时隙。
此C++11代码使用std::chrono::high_resolution_clock
来测量亚秒计时,使用std::thread
来运行三个线程。std::this_thread::sleep_for()
功能用于睡眠指定的时间。
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
void seconds()
{
using namespace std::chrono;
high_resolution_clock::time_point t1, t2;
for (unsigned i=0; i<10; ++i) {
std::cout << i << "n";
t1 = high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1));
t2 = high_resolution_clock::now();
duration<double> elapsed = duration_cast<duration<double> >(t2-t1);
std::cout << "t( " << elapsed.count() << " seconds )n";
}
}
int main()
{
std::vector<std::thread> t;
t.push_back(std::thread{[](){
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "awoke after 3n"; }});
t.push_back(std::thread{[](){
std::this_thread::sleep_for(std::chrono::seconds(7));
std::cout << "awoke after 7n"; }});
t.push_back(std::thread{seconds});
for (auto &thr : t)
thr.join();
}
很难知道这是否符合你的需求,因为这个问题缺少很多细节。在Linux下,使用进行编译
g++ -Wall -Wextra -pedantic -std=c++11 timers.cpp -o timers -lpthread
我机器上的输出:
0
( 1.00014 seconds)
1
( 1.00014 seconds)
2
awoke after 3
( 1.00009 seconds)
3
( 1.00015 seconds)
4
( 1.00011 seconds)
5
( 1.00013 seconds)
6
awoke after 7
( 1.0001 seconds)
7
( 1.00015 seconds)
8
( 1.00014 seconds)
9
( 1.00013 seconds)
其他可能感兴趣的C++11标准特性包括timed_mutex和promise/future。
这里有一种方法。我使用C++11、线程、原子和高精度时钟。调度程序将回调一个花费dt秒的函数,dt秒是自上次调用以来经过的时间。如果回调函数返回false,则可以通过调用的stop()方法来停止循环。
调度程序代码
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
#include <system_error>
class ScheduledExecutor {
public:
ScheduledExecutor()
{}
ScheduledExecutor(const std::function<bool(double)>& callback, double period)
{
initialize(callback, period);
}
void initialize(const std::function<bool(double)>& callback, double period)
{
callback_ = callback;
period_ = period;
keep_running_ = false;
}
void start()
{
keep_running_ = true;
sleep_time_sum_ = 0;
period_count_ = 0;
th_ = std::thread(&ScheduledExecutor::executorLoop, this);
}
void stop()
{
keep_running_ = false;
try {
th_.join();
}
catch(const std::system_error& /* e */)
{ }
}
double getSleepTimeAvg()
{
//TODO: make this function thread safe by using atomic types
//right now this is not implemented for performance and that
//return of this function is purely informational/debugging purposes
return sleep_time_sum_ / period_count_;
}
unsigned long getPeriodCount()
{
return period_count_;
}
private:
typedef std::chrono::high_resolution_clock clock;
template <typename T>
using duration = std::chrono::duration<T>;
void executorLoop()
{
clock::time_point call_end = clock::now();
while (keep_running_) {
clock::time_point call_start = clock::now();
duration<double> since_last_call = call_start - call_end;
if (period_count_ > 0 && !callback_(since_last_call.count()))
break;
call_end = clock::now();
duration<double> call_duration = call_end - call_start;
double sleep_for = period_ - call_duration.count();
sleep_time_sum_ += sleep_for;
++period_count_;
if (sleep_for > MinSleepTime)
std::this_thread::sleep_for(std::chrono::duration<double>(sleep_for));
}
}
private:
double period_;
std::thread th_;
std::function<bool(double)> callback_;
std::atomic_bool keep_running_;
static constexpr double MinSleepTime = 1E-9;
double sleep_time_sum_;
unsigned long period_count_;
};
示例用法
bool worldUpdator(World& w, double dt)
{
w.update(dt);
return true;
}
void main() {
//create world for your simulator
World w(...);
//start scheduler loop for every 2ms calls
ScheduledExecutor exec;
exec.initialize(
std::bind(worldUpdator, std::ref(w), std::placeholders::_1),
2E-3);
exec.start();
//main thread just checks on the results every now and then
while (true) {
if (exec.getPeriodCount() % 10000 == 0) {
std::cout << exec.getSleepTimeAvg() << std::endl;
}
}
}
还有其他关于SO的相关问题。