我正在尝试创建一个c++程序,在嵌入式硬件程序的意义上,实时工作。我的c++程序中的主循环使用了250毫秒的延迟时间。这就像:
int main()
{
do{
doSomething();
delay(250);
}while(1)
}
主循环中的延迟对我的程序的运行至关重要。我需要使用5ms延迟检查其他东西。
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 Jobn");
}
}
使用不同的线程来并行执行此任务。
要了解更多信息,请查看这里。关于StackOverflow的例子,请看这里。
您也可以在那里找到大量的教程(例如,在这里)。