Infinite function function

I am trying to run a function that will never finish (until the program is killed)

How would I start a function like this and be able to continue this function, because at the moment the program won't run after an infinite function.

Hello

Floor

+2


a source to share


5 answers


You will need to start a new stream. A given thread can only perform one function at a time. So, if you want two separate functions to run at the same time, you need multiple threads. You will need to learn multithreaded programming. If you are using Linux or another unix based system then the library to look at would be pthreads.



+10


a source


While I agree with everyone that flow is probably the easiest way, this scenario is not like what should ever happen (at least not intentionally) - it looks like it is due to a design issue ...

Why do you need a function that will run forever? What does this function do? There might be a more appropriate programming model such as a windows service or daemon process. Also, it is usually better to send a signal to the thread that it is ending, and the thread does this until it receives such a message (rather than just killing it when the application exits).



I don't know enough about what you are trying to do here, but I would suggest looking into your design and see if there is a better way.

+2


a source


Redeem it in the stream. However, it would be wise to let the function exit.

+1


a source


The execution of the "past" infinite function is not possible (if it does not end, you cannot pass it) I am assuming you want some code to loop in the background while your program does something else.

You want something like this:

#include <pthread.h>

int endLoop;

void* backgroundLoop(void* arg) {
    while (!endLoop) {
        ...
    }
    return NULL;
}

int main (int argc, char** argv) {
    pthread_t thread;
    int retval;
    ...
    // Launch background thread
    endLoop = 0;
    retval = pthread_create(&thread, NULL, backgroundLoop, NULL);

    // Continue with main function
    ...
    // Force background loop to end
    endLoop = 1;

}

      

If you are using pthreads you can find it here . If you are using any other threading library, the concept is the same, but the functions for creating / destroying threads may look different.

+1


a source


A pseudo-streaming idea based on a similar problem that I needed to fix without streaming (may or may not work for you):

  • Run the application.
  • when it gets to where the function should run, call the timer to start (very short time).
  • the timer calls back and starts an infinite function and then exits.
  • Endless function includes 10ms sleep mode and call to process all messages.
-1


a source







All Articles