c++ - 在 C++/C 中在后台运行周期性循环

标签 c++ c multithreading pthreads

我正在尝试创建实时运行的嵌入式硬件程序意义上的 C++ 程序。我的 C++ 程序中的主循环使用了 250 毫秒的延迟时间。就像:

int main()
{
  do{
   doSomething();
   delay(250);
  }while(1)
}

主循环中的延迟对于我的程序运行至关重要。 我需要使用 5 毫秒的延迟来检查其他内容。

sideJob()
{
   while(1){
    checkSomething();
    delay(5);
   }
}

如何定义函数 sideJob 与主循环同时运行。总而言之,如果可能的话,我需要通过使用简单的函数来掌握线程处理的窍门。我正在使用 Linux。任何帮助将不胜感激。

编辑:这是我目前得到的结果,但我想同时运行 sideJob 和主线程。

#include <string>
#include <iostream>
#include <thread>

using namespace std;

//The function we want to make the thread run.
void task1(string msg)
{

     cout << "sideJob Running " << msg;

}

int main()
{  
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    //Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
    while(1){
        printf("Continuous Job\n");   
    }
}

最佳答案

使用不同的线程以并行执行此任务。

要了解更多信息,请查看 here . 有关 StackOverflow 上的示例,请查看 here .

您还可以在那里找到大量教程(例如,here)。

关于c++ - 在 C++/C 中在后台运行周期性循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25416348/

相关文章:

c - 维吉尼亚密码解码无法正常工作

java - 如果在 Java 中不同步,一个线程更新的变量的值最终会被另一个线程看到吗?

c++ - 如何调用使用 IDispatch.Invoke 接收浮点值的函数?

c++ - 返回本地实例时未调用析构函数

c - K&R c中练习5.1的措辞

java - Conway 生命游戏的多线程 Java 程序 - 边界单元的竞争

c++ - 具有 pthread 实现的并发队列

c++ - 使用可变数量的模板化参数访问模板化类的成员

c++ - 将两个整数相加并打印结果,当我使用 `int` 时它是正确的但是当我使用 `double` 时它是错误的?

c - memcpy 额外的起始字符