[英]Running a periodic loop in background in C++/C
I'm trying to create C++ program in the sense of embedded hardware programs that work in real time. 我正在尝试从实时工作的嵌入式硬件程序的角度创建C ++程序。 The main loop in my C++ program uses a delay time of 250milliseconds.
我的C ++程序中的主循环使用250毫秒的延迟时间。 It's like:
就像是:
int main()
{
do{
doSomething();
delay(250);
}while(1)
}
The delay in main loop is crucial for my program to operate. 主循环中的延迟对于我的程序运行至关重要。 I need to check something else using 5ms delays.
我需要使用5ms的延迟检查其他内容。
sideJob()
{
while(1){
checkSomething();
delay(5);
}
}
How do I define the function sideJob to run at the same with the main loop. 如何定义函数sideJob与主循环同时运行。 All in all, I need to get the hang of threading by using, if possible, simple functions.
总而言之,如果可能的话,我需要使用简单的函数来摆脱线程的困扰。 I'm using Linux.
我正在使用Linux。 Any help will be greately appreaciated.
任何帮助将不胜感激。
EDIT: This is what I got so far, But I want to run the sideJob and main thread at the same time. 编辑:这是到目前为止,但是我想同时运行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");
}
}
Use different threads in order to do this tasks in parallel. 使用不同的线程以便并行执行此任务。
To learn for more about this, look here . 要了解更多有关此的信息,请看这里 。 For an example on StackOverflow, look here .
有关StackOverflow的示例,请参见此处 。
You can also find plenty of tutorials out there (for example, here ). 您还可以在那里找到很多教程(例如, 此处 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.