【问题标题】:I want two loops to run in parallel我希望两个循环并行运行
【发布时间】:2019-12-29 20:06:25
【问题描述】:

这是我正在尝试做的,我希望 main() 中的一部分代码在 连续循环 上运行以检查输入和其他内容。另一部分代码以每 X 毫秒延迟运行。

while(true) //want this to run continuously, without any delay.
{
    Input();
}

while(true) //want this to run every 1500 miliseconds.
{
    DoSomething();
    Sleep(1500); //from <windows.h> library.
}

有什么方法可以正确地做到这一点吗?

【问题讨论】:

  • 为什么不使用计时器?
  • 这能回答你的问题吗? Simple example of threading in C++
  • 使用定时器代替睡眠。你不能有 2 个while
  • 目标系统是什么?许多操作系统能够在没有线程的情况下执行此操作,例如 Windows 中的重叠 IO。或 epollselect 在 Linux 上超时。

标签: c++


【解决方案1】:

您需要运行两个线程:

void f()
{
    while(true) //want this to run continuously, without any delay.
    {
        Input();
    }
}

void g()
{    
    while(true) //want this to run every 1500 miliseconds.
    {
        DoSomething();
        Sleep(1500); //from <windows.h> library.
    }
}

int main()
{
    std::thread t1(f);
    std::thread t2(g);
    ...

【讨论】:

    【解决方案2】:

    我使用 high_resolution_clock 来记录时间。 我使用简单的 while 循环进行持续更新,并在一段时间后添加了 if 条件来执行某些特定任务。

    #include<chrono> //For clock
    using namespace std::chrono;
    
    high_resolution_clock::time_point t1, t2;
    
    int main()
    {
        t1 = high_resolution_clock::now();
        t2 = {};
    
        while(true)
        {
            CheckInput(); //Runs every time frame
    
            t2 = high_resolution_clock::now();
    
            if(duration_cast<duration<float>>(t2 - t1).count()>=waitingTime)
            {
                DoSomething();  //Runs every defautWaitTime.
                t1 = high_resolution_clock::now();
                t2 = {};
            }
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多