0

I'm trying to create C++ program in the sense of embedded hardware programs that work in real time. The main loop in my C++ program uses a delay time of 250milliseconds. 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.

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

How do I define the function sideJob to run at the same with the main loop. All in all, I need to get the hang of threading by using, if possible, simple functions. I'm using 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.

#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");   
    }
}
mozcelikors
  • 2,582
  • 8
  • 43
  • 77
  • Can't you, instead of `delay(250)`, call `checkSomething()` 50 times in a loop with `delay(5)` in between? – Igor Tandetnik Aug 21 '14 at 00:03
  • thats my last resort, cause the timing is really important and the 5ms thing and 250ms thing should not stop at any time – mozcelikors Aug 21 '14 at 00:05
  • There's plenty of pthreads tutorials out there on the internets. What have you tried so far? – MrEricSir Aug 21 '14 at 00:14
  • a simple solution, not ruled out by the information you provide, is to make two programs and run them at the same time. – Cheers and hth. - Alf Aug 21 '14 at 00:42
  • Note that if `checkSomething()` takes 1 ms to run, then you will run for 1 ms and sleep for 5 ms, for a total delay of 6 ms between periodic checks. If you use one background loop for both tasks, you will cause both tasks to drift if you don't pay attention to this detail. – indiv Aug 21 '14 at 01:25
  • @Cheersandhth.-Alf I want to do exactly what you say, but I want to pass arguments between those two executables. That information would help me plenty as well. – mozcelikors Aug 21 '14 at 09:14

1 Answers1

1

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.

You can also find plenty of tutorials out there (for example, here).

Community
  • 1
  • 1
Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54