设置C ++代码中while循环的执行率以实现实时同步

use*_*096 6 c++ synchronization while-loop

我正在使用.cpp源代码进行实时仿真。我必须采取一个样本每0.2秒(200毫秒)...有一个while循环,需要一个样品每次一步......我想这个执行while循环得到每个样品(同步200毫秒) ...我应该如何修改while循环?

while (1){
          // get a sample every 200 ms
         }
Run Code Online (Sandbox Code Playgroud)

How*_*ant 6

简单而准确的解决方案std::this_thread::sleep_until

#include "date.h"
#include <chrono>
#include <iostream>
#include <thread>

int
main()
{
    using namespace std::chrono;
    using namespace date;
    auto next = steady_clock::now();
    auto prev = next - 200ms;
    while (true)
    {
        // do stuff
        auto now = steady_clock::now();
        std::cout << round<milliseconds>(now - prev) << '\n';
        prev = now;

        // delay until time to iterate again
        next += 200ms;
        std::this_thread::sleep_until(next);
    }
}
Run Code Online (Sandbox Code Playgroud)

"date.h"延迟部分不需要。它用于提供round<duration>函数(现在在 C++17 中),并使打印durations更容易。这一切都在“做事”之下,与循环延迟无关。

只要得到一个chrono::time_point,加上你的延迟,然后睡觉直到那个time_point。只要你的“东西”比你的延迟花费的时间少,你的循环平均会忠于你的延迟。不需要其他线程。不需要计时器。只是<chrono>sleep_until

这个例子只是为我输出:

200ms
205ms
200ms
195ms
205ms
198ms
202ms
199ms
196ms
203ms
...
Run Code Online (Sandbox Code Playgroud)


Dav*_*ope 2

除非您使用实时操作系统,否则您要问的问题很棘手。

然而,Boost 有一个库可以支持你想要的。(但是,不能保证每隔 200 毫秒就会调用一次。

Boost ASIO 库可能就是您正在寻找的,以下是他们教程中的代码:

//
// timer.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main()
{
  boost::asio::io_service io;

  boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
  t.wait();

  std::cout << "Hello, world!\n";

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

链接在这里:链接到 boost asio

您可以使用此代码,然后像这样重新排列它

#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main()
{
  boost::asio::io_service io;

  while(1)
  {
    boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));

    // process your IO here - not sure how long your IO takes, so you may need to adjust your timer

    t.wait();
  }    

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

下一页还有一个异步处理 IO 的教程。